| 1 | /** |
| 2 | * Extracts content from code blocks with given path |
| 3 | * @param content The full message content |
| 4 | * @param path The file path to look for |
| 5 | * @returns The content of the code block if found, undefined otherwise |
| 6 | */ |
| 7 | export function extractContentFromCodeBlock( |
| 8 | content: string, |
| 9 | path: string, |
| 10 | ): string | undefined { |
| 11 | // Escape special characters in the path for regex |
| 12 | const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 13 | |
| 14 | // Match the code block with this path |
| 15 | // This regex looks for: |
| 16 | // 1. Code block start with the path (```[language] path) |
| 17 | // 2. The content until the closing ``` |
| 18 | // The path can be: |
| 19 | // - With language: ```typescript src/main.ts |
| 20 | // - Without language: ```src/main.ts |
| 21 | // - With line ranges: ```js src/main.ts (1-10) |
| 22 | const regex = new RegExp( |
| 23 | `\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, |
| 24 | "m", |
| 25 | ); |
| 26 | |
| 27 | const match = content.match(regex); |
| 28 | if (match && match[1]) { |
| 29 | return match[1]; |
| 30 | } |
| 31 | |
| 32 | return undefined; |
| 33 | } |