|
| 1 | +import * as vscode from "vscode"; |
| 2 | + |
| 3 | +export class GitGuardianSecretHoverProvider implements vscode.HoverProvider { |
| 4 | + public provideHover( |
| 5 | + document: vscode.TextDocument, |
| 6 | + position: vscode.Position, |
| 7 | + token: vscode.CancellationToken |
| 8 | + ): vscode.ProviderResult<vscode.Hover> { |
| 9 | + const diagnostics = vscode.languages.getDiagnostics(document.uri); |
| 10 | + |
| 11 | + for (const diagnostic of diagnostics) { |
| 12 | + if ( |
| 13 | + diagnostic.range.contains(position) && |
| 14 | + diagnostic.source === "gitguardian" |
| 15 | + ) { |
| 16 | + const hoverMessage = new vscode.MarkdownString(); |
| 17 | + hoverMessage.isTrusted = true; |
| 18 | + |
| 19 | + const diagnosticData = diagnosticToJSON(diagnostic); |
| 20 | + const encodedDiagnosticData = encodeURIComponent(diagnosticData); |
| 21 | + |
| 22 | + hoverMessage.appendMarkdown( |
| 23 | + `[GitGuardian: Ignore Secret](command:gitguardian.ignoreSecret?${encodedDiagnosticData} "Click to ignore this incident")` |
| 24 | + ); |
| 25 | + return new vscode.Hover(hoverMessage, diagnostic.range); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return null; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +function diagnosticToJSON(diagnostic: vscode.Diagnostic) { |
| 34 | + // Extract the infos useful to generate the secret name |
| 35 | + const { detector, secretSha } = extractInfosFromMessage(diagnostic.message); |
| 36 | + |
| 37 | + const diagnosticObject = { |
| 38 | + startLine: diagnostic.range.start.line, |
| 39 | + detector: detector, |
| 40 | + secretSha: secretSha, |
| 41 | + }; |
| 42 | + |
| 43 | + // Convert the object to a JSON string |
| 44 | + return JSON.stringify(diagnosticObject); |
| 45 | +} |
| 46 | + |
| 47 | +function extractInfosFromMessage(message: string): { |
| 48 | + detector: string; |
| 49 | + secretSha: string; |
| 50 | +} { |
| 51 | + const regexDetectorPattern = /Secret detected: ([a-zA-Z ]+)/; |
| 52 | + const regexShaPattern = /Secret SHA: ([a-zA-Z0-9]+)/; |
| 53 | + |
| 54 | + const matchDetector = message.match(regexDetectorPattern); |
| 55 | + const matchSha = message.match(regexShaPattern); |
| 56 | + |
| 57 | + if (matchDetector && matchSha) { |
| 58 | + const detector = matchDetector[1].trim(); |
| 59 | + const secretSha = matchSha[1].trim(); |
| 60 | + return { detector, secretSha }; |
| 61 | + } else { |
| 62 | + throw new Error("No match found"); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +export function generateSecretName( |
| 67 | + currentFile: string, |
| 68 | + uriDiagnostic: any |
| 69 | +): string { |
| 70 | + return `${uriDiagnostic.detector} - ${currentFile}:l.${uriDiagnostic.startLine}`; |
| 71 | +} |
0 commit comments