Skip to content

Commit 6a9f7af

Browse files
committed
fix: improve version field detection regex to handle any field order
Changed the regex pattern from checking only immediately after the opening brace to checking anywhere in the JSON. This handles valid JSON where the 'version' field appears after other fields like 'bomFormat' or 'specVersion'. Pattern changed from: ^\s*\{\s*"version"\s*: To: "version"\s*:\s*\d+ This prevents incorrectly adding duplicate version fields when the field already exists but not at the beginning of the JSON object.
1 parent 2fdb04d commit 6a9f7af

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/CycloneDX.MSBuild/build/CycloneDX.MSBuild.targets

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,16 +160,16 @@
160160
{
161161
var jsonContent = File.ReadAllText(SbomPath);
162162
163-
// Simple check if version field already exists using regex
164-
// Look for "version" field at the root level (after opening brace, before other fields)
165-
var versionPattern = @"^\s*\{\s*""version""\s*:";
166-
if (Regex.IsMatch(jsonContent, versionPattern, RegexOptions.Multiline))
163+
// Check if version field exists anywhere in the JSON (not just at the beginning)
164+
// This handles cases where version appears after other fields like bomFormat or specVersion
165+
var versionPattern = @"""version""\s*:\s*\d+";
166+
if (Regex.IsMatch(jsonContent, versionPattern))
167167
{
168168
Log.LogMessage(MessageImportance.Low, "[CycloneDX] SBOM already has version field");
169169
}
170170
else
171171
{
172-
// Version field doesn't exist, add it
172+
// Version field doesn't exist, add it after the opening brace
173173
// Find the opening brace and insert version field right after it
174174
var insertPattern = @"^(\s*\{)\s*$";
175175
var replacement = "$1\n \"version\": 1,";

0 commit comments

Comments
 (0)