Skip to content

Commit

Permalink
Merge pull request #630 from Checkmarx/bug/miryamFoifer/deleteZipTmpFile
Browse files Browse the repository at this point in the history
Delete Zip File (AST-40077)
  • Loading branch information
miryamfoiferCX authored Nov 19, 2024
2 parents 2ad382e + 90c92d4 commit 3cf646f
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 53 deletions.
118 changes: 77 additions & 41 deletions cxAstScan/services/CleanUpRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,62 +7,98 @@ export class CleanUpRunner {
cxWrapperFactory= new CxWrapperFactory();

async run() {
console.log("Getting job status");
const jobStatus = taskLib.getVariable('AGENT_JOBSTATUS');
console.log("Job status: " + jobStatus);
if (jobStatus !== 'Canceled') {
console.log("Pipeline not cancelled, nothing to do.");
taskLib.setResult(taskLib.TaskResult.Succeeded, "");
return;
}

const cxScanConfig = getConfiguration();
const wrapper = await this.cxWrapperFactory.createWrapper(cxScanConfig);
let data: string;

try {
data = await fs.readFile(getLogFilename(), 'utf8')
} catch (err: any) {
if (err.code === 'ENOENT') {
console.log("Log file not created. Task ended successfully")
console.log("Getting job status");
const jobStatus = taskLib.getVariable('AGENT_JOBSTATUS');
console.log("Job status: " + jobStatus);
if (jobStatus !== 'Canceled') {
console.log("Pipeline not cancelled, nothing to do.");
taskLib.setResult(taskLib.TaskResult.Succeeded, "");
} else if (err.code === 'EACCES') {
console.log('No permissions to read log file')
taskLib.setResult(taskLib.TaskResult.Failed, "")
} else {
throw err
return;
}
return
}

//Regex to get the scanID ofthe logs
const regexScanId = new RegExp(/"(ID)":"((\\"|[^"])*)"/i);
const cxScanConfig = getConfiguration();
const wrapper = await this.cxWrapperFactory.createWrapper(cxScanConfig);
let data: string;

const regexArray = regexScanId.exec(data!);
try {
data = await fs.readFile(getLogFilename(), 'utf8')
} catch (err: any) {
if (err.code === 'ENOENT') {
console.log("Log file not created. Task ended successfully")
taskLib.setResult(taskLib.TaskResult.Succeeded, "");
} else if (err.code === 'EACCES') {
console.log('No permissions to read log file')
taskLib.setResult(taskLib.TaskResult.Failed, "")
} else {
throw err
}
return
}

try {
if (regexArray) {
//m[2] is the scanID
console.log("Canceling scan with ID: " + regexArray[2])
await wrapper.scanCancel(regexArray[2]);
} else {
console.log("Scan not created. Terminating job.")
//Regex to get the scanID ofthe logs
const regexScanId = new RegExp(/"(ID)":"((\\"|[^"])*)"/i);

const regexArray = regexScanId.exec(data!);

try {
if (regexArray) {
//m[2] is the scanID
console.log("Canceling scan with ID: " + regexArray[2])
await wrapper.scanCancel(regexArray[2]);
} else {
console.log("Scan not created. Terminating job.")
}
} catch (err) {
console.log("Error canceling scan: " + err + " " + Date.now().toString())
taskLib.setResult(taskLib.TaskResult.Failed, "");
return
}

taskLib.setResult(taskLib.TaskResult.Succeeded, "");

} catch (err) {
console.log("Error canceling scan: " + err + " " + Date.now().toString())
taskLib.setResult(taskLib.TaskResult.Failed, "");
return
} finally {
await this.deleteZipFile()
await this.deleteLogFile()
}
}

taskLib.setResult(taskLib.TaskResult.Succeeded, "");
async deleteZipFile(): Promise<void> {
try {
const logFileName = getLogFilename();
const data = await fs.readFile(logFileName, 'utf-8');
const zipFilePath = this.extractZipFilePath(data);
if (zipFilePath) {
// Delete the zip file
await fs.unlink(zipFilePath);
console.log(`Deleted zip file: ${zipFilePath}`);
} else {
console.log('No zip file path found in the log file.');
}
} catch (error: any) {
if(error.code === 'ENOENT') {
console.log('Zip file already deleted.');
}
else {
console.error('Error deleting zip file', error);
}
}
}

async deleteLogFile(): Promise<void> {
try {
fs.unlink(getLogFilename())
//file removed
await fs.unlink(getLogFilename());
console.log('Log file deleted successfully.');
} catch (err) {
console.log("Unable to delete log file.", err)
console.log("Unable to delete log file.", err);
}

}

extractZipFilePath(data: string): string | null {
const zipFilePattern = /Temporary zip file path:\s*(.*)$/m;
const match = data.match(zipFilePattern);
return match ? match[1].trim() : null;
}
}
6 changes: 6 additions & 0 deletions cxAstScan/test/_suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ describe('Task runner test', function () {
assert.strictEqual(tr.stdout.indexOf('Pipeline not cancelled, nothing to do.') >= 0,
true,
"should display cleanup message: Pipeline not cancelled, nothing to do.");
assert.strictEqual(tr.stdout.indexOf('Deleted zip file') >= 0 || tr.stdout.indexOf('Zip file already deleted.') >= 0,
true,
"should display cleanup message: Deleted zip file or Zip file already deleted.");
});

it('should be success cancel scan', async function () {
Expand All @@ -92,6 +95,9 @@ describe('Task runner test', function () {
assert.strictEqual(tr.stdout.indexOf('Canceling scan with ID') >= 0,
true,
"should display cleanup message: Canceling scan with ID");
assert.strictEqual(tr.stdout.indexOf('Deleted zip file') >= 0 || tr.stdout.indexOf('Zip file already deleted.') >= 0,
true,
"should display cleanup message: Deleted zip file or Zip file already deleted.");
});

it('should be success cancel before scan start', async function () {
Expand Down
25 changes: 14 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.57.0",
"mocha": "10.7.0",
"typescript": "5.5.4"
"typescript": "^5.6.3"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com"
Expand Down

0 comments on commit 3cf646f

Please sign in to comment.