Skip to content
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
13 changes: 13 additions & 0 deletions src/service/purls.svc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ export async function extractPurls(sbom: Sbom): Promise<string[]> {
* 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)) {
Expand All @@ -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;
}
Expand Down
12 changes: 8 additions & 4 deletions test/service/purls.svc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down