From 5891cd801ac887da7013fb5637ec7dc4a28e3abc Mon Sep 17 00:00:00 2001 From: Edward Ezekiel Date: Thu, 24 Apr 2025 16:54:53 -0500 Subject: [PATCH] chore: improve error handling for purl files --- src/service/purls.svc.ts | 13 +++++++++++++ test/service/purls.svc.test.ts | 12 ++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/service/purls.svc.ts b/src/service/purls.svc.ts index 0b09ffc5..91b0cf84 100644 --- a/src/service/purls.svc.ts +++ b/src/service/purls.svc.ts @@ -38,7 +38,13 @@ export async function extractPurls(sbom: Sbom): Promise { * or a text file with one purl per line. */ export function parsePurlsFile(purlsFileString: string): string[] { + // Handle empty string + if (!purlsFileString.trim()) { + return []; + } + try { + // Try parsing as JSON first const parsed = JSON.parse(purlsFileString); if (parsed && Array.isArray(parsed.purls)) { @@ -49,11 +55,18 @@ export function parsePurlsFile(purlsFileString: string): string[] { return parsed; } } catch { + // If not JSON, try parsing as text file const lines = purlsFileString .split('\n') .map((line) => line.trim()) .filter((line) => line.length > 0 && line.startsWith('pkg:')); + // Handle single purl case (no newlines) + if (lines.length === 0 && purlsFileString.trim().startsWith('pkg:')) { + return [purlsFileString.trim()]; + } + + // Return any valid purls found if (lines.length > 0) { return lines; } diff --git a/test/service/purls.svc.test.ts b/test/service/purls.svc.test.ts index 103f60ad..87537697 100644 --- a/test/service/purls.svc.test.ts +++ b/test/service/purls.svc.test.ts @@ -105,10 +105,14 @@ pkg:npm/typescript@5.0.0`; }); }); - it('should throw error for empty file', () => { - assert.throws(() => parsePurlsFile(''), { - message: 'Invalid purls file: must be either JSON with purls array or text file with one purl per line', - }); + it('should return empty array for empty file', () => { + const result = parsePurlsFile(''); + assert.deepStrictEqual(result, []); + }); + + it('should return empty array for whitespace-only file', () => { + const result = parsePurlsFile(' \n \t '); + assert.deepStrictEqual(result, []); }); it('should throw error for file with no valid purls', () => {