Skip to content

Commit 4a137a4

Browse files
feat(utils): add watch mode trigger detection and context extraction functions
1 parent ef163a8 commit 4a137a4

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Pattern to match various "AI!" style trigger comments with possible instructions
3+
* This will match patterns like:
4+
* - "// what does this function do, AI?"
5+
* - "// change this variable name to something more precise, AI!"
6+
* - "# fix this code, AI!"
7+
*/
8+
export const TRIGGER_PATTERN =
9+
/\/\/\s*(.*),?\s*AI[!?]|#\s*(.*),?\s*AI[!?]|\/\*\s*(.*),?\s*AI[!?]\s*\*\//;
10+
11+
/**
12+
* Function to find all AI trigger matches in a file content
13+
*/
14+
export function findAllTriggers(content: string): Array<RegExpMatchArray> {
15+
const matches: Array<RegExpMatchArray> = [];
16+
const regex = new RegExp(TRIGGER_PATTERN, "g");
17+
18+
let match;
19+
while ((match = regex.exec(content)) != null) {
20+
matches.push(match);
21+
}
22+
23+
return matches;
24+
}
25+
26+
/**
27+
* Function to extract context around an AI trigger
28+
*/
29+
export function extractContextAroundTrigger(
30+
content: string,
31+
triggerMatch: RegExpMatchArray,
32+
contextSize = 15
33+
): { context: string; instruction: string } {
34+
// Get the lines of the file
35+
const lines = content.split("\n");
36+
37+
// Find the line number of the trigger
38+
const triggerPos =
39+
content.substring(0, triggerMatch.index).split("\n").length - 1;
40+
41+
// Calculate start and end lines for context
42+
const startLine = Math.max(0, triggerPos - contextSize);
43+
const endLine = Math.min(lines.length - 1, triggerPos + contextSize);
44+
45+
// Extract the context lines
46+
const contextLines = lines.slice(startLine, endLine + 1);
47+
48+
// Join the context lines back together
49+
const context = contextLines.join("\n");
50+
51+
// Extract the instruction from the capture groups
52+
// The regex has 3 capture groups for different comment styles:
53+
// Group 1: // instruction AI!
54+
// Group 2: # instruction AI!
55+
// Group 3: /* instruction AI! */
56+
const instruction =
57+
triggerMatch[1] ||
58+
triggerMatch[2] ||
59+
triggerMatch[3] ||
60+
"fix or improve this code";
61+
62+
return { context, instruction };
63+
}

0 commit comments

Comments
 (0)