Skip to content

Commit

Permalink
Merge pull request #265 from salesforcecli/u/spachbhai/W-17149811/lwc…
Browse files Browse the repository at this point in the history
…-filter

@W-17149811 - LWC parsing filtering logic
  • Loading branch information
AbhinavKumar-sf authored Dec 5, 2024
2 parents c06ff88 + dea3cdf commit 1d55c6f
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 52 deletions.
6 changes: 4 additions & 2 deletions src/commands/omnistudio/migration/assess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ export default class Assess extends OmniStudioBaseCommand {
this.ux.log(`Using Namespace: ${namespace}`);

const dataRaptorAssessmentInfos: DataRaptorAssessmentInfo[] = await drMigrator.assess();
this.ux.log('dataRaptorAssessmentInfos');
this.ux.log(dataRaptorAssessmentInfos.toString());
if (dataRaptorAssessmentInfos) {
this.ux.log('dataRaptorAssessmentInfos');
this.ux.log(dataRaptorAssessmentInfos.toString());
}
const flexCardAssessmentInfos: FlexCardAssessmentInfo[] = await flexMigrator.assess();
const omniAssessmentInfo = await osMigrator.assess(dataRaptorAssessmentInfos, flexCardAssessmentInfos);

Expand Down
4 changes: 2 additions & 2 deletions src/migration/related/ApexMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class ApexMigration extends BaseRelatedObjectMigration {
private readonly callableInterface: InterfaceImplements;
private readonly vlocityOpenInterface2: InterfaceImplements;
private readonly vlocityOpenInterface: InterfaceImplements;
private updatedNamespace = 'omnistudio';
private updatedNamespace = 'vlocity_ins';
public constructor(projectPath: string, namespace: string, org: Org) {
super(projectPath, namespace, org);
this.callableInterface = new InterfaceImplements(CALLABLE, this.namespace);
Expand All @@ -52,7 +52,7 @@ export class ApexMigration extends BaseRelatedObjectMigration {
const targetOrg: Org = this.org;
sfProject.retrieve(APEXCLASS, targetOrg.getUsername());
const apexAssessmentInfos = this.processApexFiles(this.projectPath);
// sfProject.deploy(APEXCLASS, targetOrg.getUsername());
sfProject.deploy(APEXCLASS, targetOrg.getUsername());
shell.cd(pwd);
return apexAssessmentInfos;
}
Expand Down
21 changes: 14 additions & 7 deletions src/migration/related/LwcMigration.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import * as shell from 'shelljs';
import { Org } from '@salesforce/core';
Expand Down Expand Up @@ -26,7 +27,7 @@ export class LwcMigration extends BaseRelatedObjectMigration {
const type = 'assessment';
const pwd = shell.pwd();
shell.cd(this.projectPath);
sfProject.retrieve(LWCTYPE, this.org.getUsername());
// sfProject.retrieve(LWCTYPE, this.org.getUsername());
const filesMap = this.processLwcFiles(this.projectPath);
shell.cd(pwd);
return this.processFiles(filesMap, type);
Expand All @@ -49,7 +50,7 @@ export class LwcMigration extends BaseRelatedObjectMigration {
dir += LWC_DIR_PATH;
let filesMap: Map<string, File[]>;
try {
filesMap = fileutil.readAllFiles(dir);
filesMap = fileutil.readAndProcessFiles(dir, 'OmniScript Auto-generated');
} catch (error) {
Logger.logger.error('Error in reading files', error);
}
Expand All @@ -62,18 +63,24 @@ export class LwcMigration extends BaseRelatedObjectMigration {
const jsonData: LWCAssessmentInfo[] = [];
fileMap.forEach((fileList, dir) => {
const changeInfos: FileChangeInfo[] = [];
if (dir !== 'lwc' && !dir.endsWith('English') && !dir.includes('_') && !dir.startsWith('cf')) {
if (
dir !== 'lwc' &&
!dir.endsWith('MultiLanguage') &&
!dir.endsWith('English') &&
!dir.includes('_') &&
!dir.startsWith('cf') &&
!dir.startsWith('Omniscript') &&
!dir.includes('Util') &&
!dir.includes('lodash')
) {
for (const file of fileList) {
if (this.isValideFile(file.name)) {
const processor = FileProcessorFactory.getFileProcessor(file.ext);
if (processor != null) {
const path = file.location;
const name = file.name + file.ext;
if (file.ext === 'xml') {
// if (fileutil.isAutogenratedFile(path)) { }
}
const diff = processor.process(file, type, this.namespace);
if (diff != null) {
if (diff !== undefined && diff !== '') {
const fileInfo: FileChangeInfo = {
path,
name,
Expand Down
60 changes: 60 additions & 0 deletions src/utils/file/fileutil.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable no-console */
import * as fs from 'fs';
Expand Down Expand Up @@ -71,6 +73,64 @@ export class fileutil {
throw error;
}
}

public static readAndProcessFiles(
baseDir: string,
searchString: string,
fileMap: Map<string, File[]> = new Map<string, File[]>()
): Map<string, File[]> {
const subDirectories = fs.readdirSync(baseDir).filter((dir) => {
const fullPath = path.join(baseDir, dir);
return fs.statSync(fullPath).isDirectory();
});

for (const subDirectory of subDirectories) {
console.log(`Processing subdirectory: ${subDirectory}`);
const subDirPath = path.join(baseDir, subDirectory);

// Check the XML file for the substring
const xmlFilePath = path.join(subDirPath, `${subDirectory}.js-meta.xml`);
if (fs.existsSync(xmlFilePath)) {
if (this.doesSubstringExist(xmlFilePath, searchString)) {
console.log(`Substring found in ${xmlFilePath}. Skipping all files in ${subDirectory}.`);
continue; // Move to the next subdirectory
}
}

// Process all files if substring is not found
const currentDirFiles: File[] = [];
const files = fs
.readdirSync(subDirPath)
.filter((file) => file.endsWith('.html') || file.endsWith('.js') || file.endsWith('.xml'));
files.forEach((file) => {
const filePath = path.join(subDirPath, file);
console.log(`Processing file: ${filePath}`);
const name = path.parse(file).name;
const ext = path.parse(file).ext;
const filepath = path.resolve(subDirPath, file);
currentDirFiles.push(new File(name, filepath, ext));
fileMap.set(path.basename(subDirPath), currentDirFiles);
});
}
return fileMap;
}

/**
* Check if a substring exists in an XML file
*
* @param filePath Path of the XML file
* @param searchString Substring to search for
* @returns true if substring exists, otherwise false
*/
private static doesSubstringExist = (filePath: string, searchString: string): boolean => {
try {
const fileContent = fs.readFileSync(filePath, 'utf-8');
return fileContent.includes(searchString);
} catch (error) {
console.error(`Error reading file ${filePath}:`, error);
return false;
}
};
}

export class File {
Expand Down
6 changes: 3 additions & 3 deletions src/utils/formula/FormulaUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ function getReplacedformulaString(
const startParanthIndex = startIndex + formulaName.length;
const endParanthIndex = getClosingIndexOfParantheses(formulaExpression, startParanthIndex);
const newFormulaExpression =
'Function(' +
className +
'FUNCTION(' +
`'${className}'` +
',' +
methodName +
`'${methodName}'` +
',' +
formulaExpression.substring(startParanthIndex + 1, endParanthIndex) +
')';
Expand Down
2 changes: 1 addition & 1 deletion src/utils/generatePackageXml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class generatePackageXml {
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
${apexXml}
${lwcXml}
${additionalTypes}
${additionalTypes}
<version>57.0</version>
</Package>
`;
Expand Down
80 changes: 46 additions & 34 deletions src/utils/lwcparser/fileutils/FileDiffUtil.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,59 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { createPatch } from 'diff';
import { Logger } from '../../../utils/logger';

export class FileDiffUtil {
public getFileDiff(filename: string, originalFileContent: string, modifiedFileContent: string): string {
const patch: string = createPatch(filename, originalFileContent, modifiedFileContent);

// Split the patch into lines
const patchLines = patch.split('\n');
const patch: string = createPatch('', originalFileContent, modifiedFileContent);
try {
// Split the patch into lines
const patchLines = patch.split('\n');

// Initialize variables to track line numbers
let oldLineNumber = 1;
let newLineNumber = 1;
// Initialize variables to track line numbers
let oldLineNumber = 1;
let newLineNumber = 1;

// Initialize result as HTML string
let result = '';
// Initialize result as HTML string
let result = '';

patchLines.forEach((line) => {
// Parse the hunk header (e.g., @@ -2,3 +2,3 @@)
const hunkHeader = /^@@ -(\d+),\d+ \+(\d+),\d+ @@/;
const match = hunkHeader.exec(line);
patchLines.forEach((line) => {
// Parse the hunk header (e.g., @@ -2,3 +2,3 @@)
const hunkHeader = /^@@ -(\d+),\d+ \+(\d+),\d+ @@/;
const match = hunkHeader.exec(line);

if (match) {
oldLineNumber = parseInt(match[1], 10);
newLineNumber = parseInt(match[2], 10);
result += `<div>${this.escapeHtml(line)}</div>`;
} else if (line.startsWith('-')) {
result += `<div style="color: red;">- Line ${oldLineNumber}: ${this.escapeHtml(line.slice(1))}</div>`;
oldLineNumber++;
} else if (line.startsWith('+')) {
result += `<div style="color: green;">+ Line ${newLineNumber}: ${this.escapeHtml(line.slice(1))}</div>`;
newLineNumber++;
} else if (line.startsWith(' ')) {
// Unchanged line, just increment both line counters
result += `<div>${this.escapeHtml(line)}</div>`;
oldLineNumber++;
newLineNumber++;
}
});
// Return the result string with color codes
return result;
if (match) {
oldLineNumber = parseInt(match[1], 10);
newLineNumber = parseInt(match[2], 10);
} else if (line.startsWith('-')) {
// Skip the first line difference
if (oldLineNumber === 1) {
oldLineNumber++;
return;
}
result += `<div style="color: red;">- Line ${oldLineNumber}: ${this.escapeHtml(line.slice(1))}</div>`;
oldLineNumber++;
} else if (line.startsWith('+')) {
// Skip the first line difference
if (newLineNumber === 1) {
newLineNumber++;
return;
}
result += `<div style="color: green;">+ Line ${newLineNumber}: ${this.escapeHtml(line.slice(1))}</div>`;
newLineNumber++;
} else if (line.startsWith(' ')) {
// Unchanged line, skip it
oldLineNumber++;
newLineNumber++;
}
});
// Return the result string, or an empty string if no differences
return result.trim() ? result : '';
} catch (error) {
Logger.logger.error('Error in FileDiffUtil', error.message);
}
}

escapeHtml(text: string): string {
Expand Down
7 changes: 4 additions & 3 deletions test/utils/formula/formulaUtil.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('FormulaUtilTest', () => {
const inputString = "TESTMETHODFIRST('hello','bye')";
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const result = getReplacedString(namespacePrefix, inputString, mockedFunctionDefinitionMetadata);
const expectedResult = "Function(testClassFirst,testMethodFirst,'hello','bye')";
const expectedResult = "FUNCTION('testClassFirst','testMethodFirst','hello','bye')";

expect(result).to.be.equal(expectedResult);
});
Expand All @@ -23,7 +23,8 @@ describe('FormulaUtilTest', () => {
const inputString = "TESTMETHODFIRST('hello',TESTMETHOD('bye'))";
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const result = getReplacedString(namespacePrefix, inputString, mockedFunctionDefinitionMetadata);
const expectedResult = "Function(testClassFirst,testMethodFirst,'hello',Function(testClass,testMethod,'bye'))";
const expectedResult =
"FUNCTION('testClassFirst','testMethodFirst','hello',FUNCTION('testClass','testMethod','bye'))";

expect(result).to.be.equal(expectedResult);
});
Expand All @@ -36,7 +37,7 @@ describe('FormulaUtilTest', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const result = getReplacedString(namespacePrefix, inputString, mockedFunctionDefinitionMetadata);
const expectedResult =
"Function(testClassFirst,testMethodFirst,'hello',Function(testClass,testMethod,Function(testClassFirst,testMethodFirst,'bye','check')))";
"FUNCTION('testClassFirst','testMethodFirst','hello',FUNCTION('testClass','testMethod',FUNCTION('testClassFirst','testMethodFirst','bye','check')))";
expect(result).to.be.equal(expectedResult);
});
});
Expand Down

0 comments on commit 1d55c6f

Please sign in to comment.