Skip to content

Commit fc60ec7

Browse files
authored
chore: improve error handling for purl files (#201)
1 parent 9ae477d commit fc60ec7

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

src/service/purls.svc.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,13 @@ export async function extractPurls(sbom: Sbom): Promise<string[]> {
3838
* or a text file with one purl per line.
3939
*/
4040
export function parsePurlsFile(purlsFileString: string): string[] {
41+
// Handle empty string
42+
if (!purlsFileString.trim()) {
43+
return [];
44+
}
45+
4146
try {
47+
// Try parsing as JSON first
4248
const parsed = JSON.parse(purlsFileString);
4349

4450
if (parsed && Array.isArray(parsed.purls)) {
@@ -49,11 +55,18 @@ export function parsePurlsFile(purlsFileString: string): string[] {
4955
return parsed;
5056
}
5157
} catch {
58+
// If not JSON, try parsing as text file
5259
const lines = purlsFileString
5360
.split('\n')
5461
.map((line) => line.trim())
5562
.filter((line) => line.length > 0 && line.startsWith('pkg:'));
5663

64+
// Handle single purl case (no newlines)
65+
if (lines.length === 0 && purlsFileString.trim().startsWith('pkg:')) {
66+
return [purlsFileString.trim()];
67+
}
68+
69+
// Return any valid purls found
5770
if (lines.length > 0) {
5871
return lines;
5972
}

test/service/purls.svc.test.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,14 @@ pkg:npm/typescript@5.0.0`;
105105
});
106106
});
107107

108-
it('should throw error for empty file', () => {
109-
assert.throws(() => parsePurlsFile(''), {
110-
message: 'Invalid purls file: must be either JSON with purls array or text file with one purl per line',
111-
});
108+
it('should return empty array for empty file', () => {
109+
const result = parsePurlsFile('');
110+
assert.deepStrictEqual(result, []);
111+
});
112+
113+
it('should return empty array for whitespace-only file', () => {
114+
const result = parsePurlsFile(' \n \t ');
115+
assert.deepStrictEqual(result, []);
112116
});
113117

114118
it('should throw error for file with no valid purls', () => {

0 commit comments

Comments
 (0)