Skip to content

Commit f51e131

Browse files
authored
feat: [OSM-2902] Parse global.json with a JSONC parser (#93)
1 parent 4122929 commit f51e131

File tree

3 files changed

+6
-7
lines changed

3 files changed

+6
-7
lines changed

lib/index.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import 'source-map-support/register';
22
import * as fs from 'fs';
33
import * as path from 'path';
44
import { OpenSourceEcosystems } from '@snyk/error-catalog-nodejs-public';
5+
import * as jsonc from 'jsonc-parser';
56

67
import {
78
DepType,
@@ -323,13 +324,9 @@ function extractTargetSdkFromGlobalJson(
323324
manifestFileContents: string,
324325
): string | undefined {
325326
try {
326-
// Remove /* */ comments from the JSON string (if any)
327-
// It's allowed: https://learn.microsoft.com/en-us/dotnet/core/tools/global-json#comments-in-globaljson
328-
const jsonWithoutComments = manifestFileContents.replace(
329-
/\/\*[\s\S]*?\*\/|\/\/.*$/gm,
330-
'',
331-
);
332-
const globalJsonAsObj = JSON.parse(jsonWithoutComments);
327+
// Use a JSONC parser as that's the format of global.json, which accepts comments,
328+
// see https://learn.microsoft.com/en-us/dotnet/core/tools/global-json#comments-in-globaljson
329+
const globalJsonAsObj = jsonc.parse(manifestFileContents);
333330
return globalJsonAsObj?.sdk?.version;
334331
} catch (err: any) {
335332
throw new Error(

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"homepage": "https://github.com/snyk/dotnet-deps-parser#readme",
3030
"dependencies": {
3131
"@snyk/error-catalog-nodejs-public": "^4.0.1",
32+
"jsonc-parser": "^3.3.1",
3233
"lodash": "^4.17.21",
3334
"source-map-support": "^0.5.21",
3435
"xml2js": "0.6.2"

test/fixtures/dotnet-core-global-json/global_with_comments.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
// This is a comment.
33
"sdk": {
4+
"comment": "This is a comment with a URL https://google.com",
45
"version": "7.0.100" /* This is comment 2*/
56
/* This is a
67
multiline comment.*/

0 commit comments

Comments
 (0)