Skip to content

Commit 7a32785

Browse files
committed
Filter alerts by pr-diff-range JSON file
1 parent 7116241 commit 7a32785

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/upload-lib.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,7 @@ export async function uploadFiles(
578578
features,
579579
logger,
580580
);
581+
sarif = filterAlertsByDiffRange(sarif);
581582
sarif = await fingerprints.addFingerprints(sarif, checkoutPath, logger);
582583

583584
const analysisKey = await api.getAnalysisKey();
@@ -848,3 +849,57 @@ export class InvalidSarifUploadError extends Error {
848849
super(message);
849850
}
850851
}
852+
853+
function filterAlertsByDiffRange(sarif: SarifFile): SarifFile {
854+
const diffRangeFilePath = path.join(
855+
actionsUtil.getTemporaryDirectory(),
856+
"pr-diff-range",
857+
"pr-diff-range.json",
858+
);
859+
860+
if (!fs.existsSync(diffRangeFilePath)) {
861+
return sarif;
862+
}
863+
864+
const diffRanges = JSON.parse(
865+
fs.readFileSync(diffRangeFilePath, "utf8"),
866+
) as Array<{
867+
path: string;
868+
startLine: number;
869+
endLine: number;
870+
}>;
871+
872+
// CodeQL always uses forward slashes as the path separator, so on Windows we
873+
// need to replace any backslashes with forward slashes.
874+
const checkoutPath = actionsUtil
875+
.getRequiredInput("checkout_path")
876+
.replaceAll(path.sep, "/");
877+
878+
for (const run of sarif.runs) {
879+
if (run.results) {
880+
run.results = run.results.filter((result) => {
881+
const locations = [
882+
...(result.locations || []).map((loc) => loc.physicalLocation),
883+
...(result.relatedLocations || []).map((loc) => loc.physicalLocation),
884+
];
885+
886+
return locations.some((physicalLocation) => {
887+
const uri = physicalLocation?.artifactLocation?.uri;
888+
const startLine = physicalLocation?.region?.startLine;
889+
if (!uri || !startLine) {
890+
return false;
891+
}
892+
const locationPath = path.join(checkoutPath, uri);
893+
return diffRanges.some(
894+
(range) =>
895+
range.path === locationPath &&
896+
((range.startLine <= startLine && range.endLine >= startLine) ||
897+
(range.startLine === 0 && range.endLine === 0)),
898+
);
899+
});
900+
});
901+
}
902+
}
903+
904+
return sarif;
905+
}

src/util.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ export interface SarifResult {
9696
};
9797
};
9898
}>;
99+
relatedLocations?: Array<{
100+
physicalLocation: {
101+
artifactLocation: {
102+
uri: string;
103+
};
104+
region?: {
105+
startLine?: number;
106+
};
107+
};
108+
}>;
99109
partialFingerprints: {
100110
primaryLocationLineHash?: string;
101111
};

0 commit comments

Comments
 (0)