|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import { TodoItem } from './types'; |
| 4 | + |
| 5 | +const COMMENT_PATTERNS = [ |
| 6 | + { ext: ['.ts', '.js', '.java', '.go'], pattern: /^\s*\/\/\s*(.*)$/ }, |
| 7 | + { ext: ['.py', '.sh', '.rb'], pattern: /^\s*#\s*(.*)$/ }, |
| 8 | + { ext: ['.html', '.xml'], pattern: /<!--\s*(.*?)\s*-->/ } |
| 9 | +]; |
| 10 | + |
| 11 | +const TAG_REGEX = /(TODO|FIXME|BUG|HACK)(\([^)]*\))?:?\s*(.*)/i; |
| 12 | + |
| 13 | +function extractMetadata(str: string): Record<string, string> { |
| 14 | + const meta: Record<string, string> = {}; |
| 15 | + const match = str.match(/\((.*?)\)/); |
| 16 | + if (match) { |
| 17 | + const content = match[1]; |
| 18 | + content.split(',').forEach(pair => { |
| 19 | + const [key, val] = pair.split('=').map(s => s.trim()); |
| 20 | + if (key && val) meta[key] = val; |
| 21 | + }); |
| 22 | + } |
| 23 | + return meta; |
| 24 | +} |
| 25 | + |
| 26 | +export function extractTodosFromFile(filePath: string): TodoItem[] { |
| 27 | + const ext = path.extname(filePath); |
| 28 | + const pattern = COMMENT_PATTERNS.find(p => p.ext.includes(ext)); |
| 29 | + if (!pattern) return []; |
| 30 | + |
| 31 | + const lines = fs.readFileSync(filePath, 'utf-8').split('\n'); |
| 32 | + const todos: TodoItem[] = []; |
| 33 | + |
| 34 | + lines.forEach((line, idx) => { |
| 35 | + const commentMatch = line.match(pattern.pattern); |
| 36 | + if (commentMatch) { |
| 37 | + const comment = commentMatch[1]; |
| 38 | + const tagMatch = comment.match(TAG_REGEX); |
| 39 | + if (tagMatch) { |
| 40 | + const [_, tag, metaRaw, text] = tagMatch; |
| 41 | + const metadata = metaRaw ? extractMetadata(metaRaw) : undefined; |
| 42 | + todos.push({ |
| 43 | + file: filePath, |
| 44 | + line: idx + 1, |
| 45 | + tag, |
| 46 | + text: text.trim(), |
| 47 | + metadata |
| 48 | + }); |
| 49 | + } |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + return todos; |
| 54 | +} |
0 commit comments