11import * as sarif from "sarif" ;
22import {
3+ parseHighlightedLine ,
34 parseSarifPlainTextMessage ,
45 parseSarifRegion ,
56} from "../pure/sarif-utils" ;
@@ -15,6 +16,11 @@ import {
1516 HighlightedRegion ,
1617} from "./shared/analysis-result" ;
1718
19+ // A line of more than 8k characters is probably generated.
20+ const CODE_SNIPPET_LARGE_LINE_SIZE_LIMIT = 8192 ;
21+ // If less than 1% of the line is highlighted, we consider it a small snippet.
22+ const CODE_SNIPPET_HIGHLIGHTED_REGION_MINIMUM_RATIO = 0.01 ;
23+
1824const defaultSeverity = "Warning" ;
1925
2026export function extractAnalysisAlerts (
@@ -163,17 +169,44 @@ export function tryGetRule(
163169}
164170
165171function getCodeSnippet (
172+ contextRegion ?: sarif . Region ,
166173 region ?: sarif . Region ,
167- alternateRegion ?: sarif . Region ,
168174) : CodeSnippet | undefined {
169- region = region ?? alternateRegion ;
175+ const actualRegion = contextRegion ?? region ;
170176
171- if ( ! region ) {
177+ if ( ! actualRegion ) {
172178 return undefined ;
173179 }
174180
175- const text = region . snippet ?. text || "" ;
176- const { startLine, endLine } = parseSarifRegion ( region ) ;
181+ const text = actualRegion . snippet ?. text || "" ;
182+ const { startLine, endLine } = parseSarifRegion ( actualRegion ) ;
183+
184+ if (
185+ contextRegion &&
186+ region &&
187+ text . length > CODE_SNIPPET_LARGE_LINE_SIZE_LIMIT
188+ ) {
189+ const code = text . split ( "\n" ) ;
190+
191+ const highlightedRegion = parseSarifRegion ( region ) ;
192+
193+ const highlightedLines = code . map ( ( line , index ) => {
194+ return parseHighlightedLine ( line , startLine + index , highlightedRegion ) ;
195+ } ) ;
196+
197+ const highlightedCharactersCount = highlightedLines . reduce (
198+ ( a , line ) => a + line . highlightedSection . length ,
199+ 0 ,
200+ ) ;
201+
202+ const highlightedRatio = highlightedCharactersCount / text . length ;
203+
204+ if ( highlightedRatio < CODE_SNIPPET_HIGHLIGHTED_REGION_MINIMUM_RATIO ) {
205+ // If not enough is highlighted and the snippet is large, it's probably generated or bundled code and
206+ // we don't want to show it.
207+ return undefined ;
208+ }
209+ }
177210
178211 return {
179212 startLine,
0 commit comments