@@ -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+ }
0 commit comments