Merge pull request #6221 from continuedev/tomasz/regex-trigger
Regex rule trigger
This commit is contained in:
commit
d3d201315d
12 changed files with 520 additions and 42 deletions
2
core/index.d.ts
vendored
2
core/index.d.ts
vendored
|
|
@ -1577,12 +1577,12 @@ export interface RuleWithSource {
|
|||
slug?: string;
|
||||
source: RuleSource;
|
||||
globs?: string | string[];
|
||||
regex?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
provider?: string;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
} from "../..";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
|
||||
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
|
|
@ -52,6 +53,47 @@ const matchesGlobs = (
|
|||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if file content matches any of the provided regex regex
|
||||
*
|
||||
* @param fileContent - The content of the file to check
|
||||
* @param regex - A single regex pattern string or array of regex pattern strings
|
||||
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
|
||||
*/
|
||||
const contentMatchesRegex = (
|
||||
fileContent: string,
|
||||
regex: string | string[],
|
||||
): boolean => {
|
||||
// Handle single string pattern
|
||||
if (typeof regex === "string") {
|
||||
try {
|
||||
const expression = new RegExp(regex);
|
||||
return expression.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${regex}`, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle array of regex
|
||||
if (Array.isArray(regex)) {
|
||||
if (regex.length === 0) return true;
|
||||
|
||||
// Content must match at least one pattern
|
||||
return regex.some((pattern) => {
|
||||
try {
|
||||
const regex = new RegExp(pattern);
|
||||
return regex.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${pattern}`, e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a file path is within a specific directory or its subdirectories
|
||||
*
|
||||
|
|
@ -103,25 +145,67 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Root-level rules with no globs are implicitly global
|
||||
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
|
||||
// Root-level rules with no globs or regex are implicitly global
|
||||
if (
|
||||
isRootLevelRule(rule) &&
|
||||
!rule.globs &&
|
||||
!rule.regex &&
|
||||
rule.alwaysApply !== false
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const checkGlobsAndRegex = ({
|
||||
rule,
|
||||
filePaths,
|
||||
fileContents,
|
||||
}: {
|
||||
rule: RuleWithSource;
|
||||
filePaths: string[];
|
||||
fileContents: Record<string, string>;
|
||||
}) => {
|
||||
const matchingFiles = rule.globs
|
||||
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
|
||||
: filePaths;
|
||||
|
||||
// If no files match the globs, don't apply the rule
|
||||
if (matchingFiles.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now check for pattern matches in file contents if regex are specified
|
||||
if (rule.regex) {
|
||||
// Check if any of the matching files also match the content regex
|
||||
return matchingFiles.some((filePath) => {
|
||||
const content = fileContents[filePath];
|
||||
// If we don't have the content, we can't check regex
|
||||
if (!content) return false;
|
||||
return contentMatchesRegex(content, rule.regex!);
|
||||
});
|
||||
}
|
||||
|
||||
// If we have no regex or if we couldn't check regex (no content),
|
||||
// just go with the glob matches
|
||||
return matchingFiles.length > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a rule should be applied based on its alwaysApply property and file path matching
|
||||
* Determines if a rule should be applied based on its properties and file matching
|
||||
*
|
||||
* @param rule - The rule to check
|
||||
* @param filePaths - Array of file paths to check against the rule's globs
|
||||
* @param fileContents - Map of file paths to their contents for pattern matching
|
||||
* @param rulePolicies - Optional policies that can override normal rule behavior
|
||||
* @returns true if the rule should be applied, false otherwise
|
||||
*/
|
||||
export const shouldApplyRule = (
|
||||
rule: RuleWithSource,
|
||||
filePaths: string[],
|
||||
rulePolicies: RulePolicies = {},
|
||||
fileContents: Record<string, string> = {},
|
||||
): boolean => {
|
||||
const policy = rulePolicies[rule.name || ""];
|
||||
|
||||
|
|
@ -157,40 +241,27 @@ export const shouldApplyRule = (
|
|||
isFileInDirectory(filePath, ruleDirPath),
|
||||
);
|
||||
|
||||
// If no files are in this directory, don't apply the rule
|
||||
if (filesInRuleDirectory.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we have globs, check if any files in this directory match them
|
||||
if (rule.globs) {
|
||||
return filesInRuleDirectory.some((filePath) =>
|
||||
matchesGlobs(filePath, rule.globs),
|
||||
);
|
||||
}
|
||||
|
||||
// No globs but files are in this directory, so apply the rule
|
||||
return true;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths: filesInRuleDirectory,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
}
|
||||
|
||||
// For root-level rules:
|
||||
|
||||
// If alwaysApply is explicitly false, only apply if there are globs AND they match
|
||||
if (rule.alwaysApply === false) {
|
||||
if (!rule.globs) {
|
||||
return false;
|
||||
}
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
// If alwaysApply is explicitly false, we need to check globs and/or regex
|
||||
if (
|
||||
rule.alwaysApply === false &&
|
||||
rule.globs === undefined &&
|
||||
rule.regex === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Default behavior for root rules with globs:
|
||||
// - Only apply if they match the globs
|
||||
if (rule.globs) {
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
}
|
||||
|
||||
// This point should not be reached as we've handled all cases above
|
||||
return false;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -220,10 +291,34 @@ export const getApplicableRules = (
|
|||
// Combine file paths from both sources
|
||||
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
|
||||
|
||||
// Create a map of file paths to their contents for pattern matching
|
||||
const fileContents: Record<string, string> = {};
|
||||
|
||||
// Extract contents from context items with file URIs
|
||||
contextItems.forEach((item) => {
|
||||
if (item.uri?.type === "file" && item.uri?.value) {
|
||||
fileContents[item.uri.value] = item.content;
|
||||
}
|
||||
});
|
||||
|
||||
// Extract contents from code blocks in the message for paths that don't have content yet
|
||||
if (userMessage) {
|
||||
const messageContent = renderChatMessage(userMessage);
|
||||
filePathsFromMessage.forEach((path) => {
|
||||
// Only extract content if we don't already have it from context items
|
||||
if (!fileContents[path]) {
|
||||
const blockContent = extractContentFromCodeBlock(messageContent, path);
|
||||
if (blockContent) {
|
||||
fileContents[path] = blockContent;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
|
||||
// and path matching in a consistent way
|
||||
const applicableRules = rules.filter((rule) =>
|
||||
shouldApplyRule(rule, allFilePaths, rulePolicies),
|
||||
shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
|
||||
);
|
||||
|
||||
return applicableRules;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,14 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { shouldApplyRule } from "./getSystemMessageWithRules";
|
||||
import {
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import {
|
||||
getApplicableRules,
|
||||
shouldApplyRule,
|
||||
} from "./getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
describe("Rule colocation glob matching", () => {
|
||||
|
|
@ -244,3 +252,228 @@ describe("Rule policies", () => {
|
|||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Content pattern matching", () => {
|
||||
it("should apply rules when file content matches pattern", () => {
|
||||
// Rule with pattern to match React component files
|
||||
const reactComponentRule: RuleWithSource = {
|
||||
name: "React Component Rule",
|
||||
rule: "Follow React component standards",
|
||||
regex: "export (function|const) \\w+.*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// File that matches the pattern
|
||||
const filePath = "src/components/Button.tsx";
|
||||
const fileContents = {
|
||||
[filePath]:
|
||||
"export function Button() { return <button>Click me</button> }",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
|
||||
).toBe(true);
|
||||
|
||||
// File that doesn't match the pattern
|
||||
const nonMatchingContents = {
|
||||
[filePath]:
|
||||
"import React from 'react'; // Just an import, not a component",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should support multiple regex regex as an array", () => {
|
||||
// Rule with multiple regex
|
||||
const multiPatternRule: RuleWithSource = {
|
||||
name: "Multi-Pattern Rule",
|
||||
rule: "Apply to functions or classes",
|
||||
regex: ["function\\s+\\w+", "class\\s+\\w+"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
|
||||
// Content with function - should match
|
||||
const functionContent = {
|
||||
[filePath]: "function formatDate(date) { return date.toISOString(); }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with class - should match
|
||||
const classContent = {
|
||||
[filePath]:
|
||||
"class DateFormatter { format(date) { return date.toISOString(); } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with neither - should not match
|
||||
const nonMatchingContent = {
|
||||
[filePath]: "const PI = 3.14159;",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should apply rules based on both globs and regex when both are specified", () => {
|
||||
// Rule with both glob and pattern restrictions
|
||||
const typescriptClassRule: RuleWithSource = {
|
||||
name: "TypeScript Class Rule",
|
||||
rule: "Follow class standards in TypeScript",
|
||||
globs: "**/*.ts",
|
||||
regex: "class\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
const tsFilePath = "src/models/User.ts";
|
||||
const jsFilePath = "src/models/Product.js";
|
||||
|
||||
// TypeScript file with class - should match
|
||||
const tsClassContent = {
|
||||
[tsFilePath]: "export class User { constructor(public name: string) {} }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
|
||||
).toBe(true);
|
||||
|
||||
// TypeScript file without class - should not match
|
||||
const tsNonClassContent = {
|
||||
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
|
||||
).toBe(false);
|
||||
|
||||
// JavaScript file with class - should not match due to glob
|
||||
const jsClassContent = {
|
||||
[jsFilePath]:
|
||||
"export class Product { constructor(name) { this.name = name; } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should extract file content from messages for pattern matching", () => {
|
||||
// Rule with pattern
|
||||
const arrowFunctionRule: RuleWithSource = {
|
||||
name: "Arrow Function Rule",
|
||||
rule: "Use arrow functions for better this binding",
|
||||
regex: "const\\s+\\w+\\s*=\\s*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Message with code block containing a matching pattern
|
||||
const messageWithArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
|
||||
};
|
||||
|
||||
// Create context item to match the file in the message
|
||||
const contextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "const format = (date) => {\n return date.toISOString();\n};",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should match the pattern
|
||||
const applicableRules = getApplicableRules(
|
||||
messageWithArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[contextItem],
|
||||
);
|
||||
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Arrow Function Rule");
|
||||
|
||||
// Message with code block that doesn't match the pattern
|
||||
const messageWithoutArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
|
||||
};
|
||||
|
||||
// Context item with non-matching content
|
||||
const nonMatchingContextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "function format(date) {\n return date.toISOString();\n}",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should not match the pattern
|
||||
const nonApplicableRules = getApplicableRules(
|
||||
messageWithoutArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[nonMatchingContextItem],
|
||||
);
|
||||
|
||||
expect(nonApplicableRules).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle invalid regex regex gracefully", () => {
|
||||
// Rule with invalid regex pattern
|
||||
const invalidRegexRule: RuleWithSource = {
|
||||
name: "Invalid Regex Rule",
|
||||
rule: "This rule has an invalid regex pattern",
|
||||
regex: "([unclosed parenthesis",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
const fileContents = {
|
||||
[filePath]: "function helper() { return true; }",
|
||||
};
|
||||
|
||||
// Should not throw an error but gracefully not apply the rule
|
||||
expect(
|
||||
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should respect directory restrictions for pattern rules", () => {
|
||||
// Rule with pattern in a nested directory
|
||||
const nestedPatternRule: RuleWithSource = {
|
||||
name: "Nested Pattern Rule",
|
||||
rule: "Apply only to model files with interfaces",
|
||||
regex: "interface\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
// File in the correct directory with matching content
|
||||
const modelFilePath = "src/models/User.ts";
|
||||
const modelContents = {
|
||||
[modelFilePath]: "export interface User { id: string; name: string; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
|
||||
).toBe(true);
|
||||
|
||||
// File outside the directory with matching content - should not match
|
||||
const utilFilePath = "src/utils/types.ts";
|
||||
const utilContents = {
|
||||
[utilFilePath]:
|
||||
"export interface Config { apiUrl: string; timeout: number; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
|
||||
|
||||
describe("extractContentFromCodeBlock", () => {
|
||||
it("should extract content from code block with language and filepath", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with filepath only (no language)", () => {
|
||||
const content = "```test.js\nclass Calculator { }\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with line ranges", () => {
|
||||
const content = "```js test.js (19-25)\nfunction test() {}\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple code blocks and find the right one", () => {
|
||||
const content =
|
||||
"```typescript src/main.ts\nconst x = 1;\n```\n" +
|
||||
"```test.js\nclass Calculator { }\n```\n" +
|
||||
"```js utils.js (19-25)\nfunction test() {}\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle paths with special regex characters", () => {
|
||||
const content =
|
||||
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
|
||||
).toBe("const special = true;");
|
||||
});
|
||||
|
||||
it("should handle multiline content", () => {
|
||||
const content =
|
||||
"```typescript src/multi-line.ts\n" +
|
||||
"function example() {\n" +
|
||||
" const x = 1;\n" +
|
||||
" return x + 2;\n" +
|
||||
"}\n" +
|
||||
"```";
|
||||
|
||||
const expected =
|
||||
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return undefined when path doesn't exist in any code block", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "nonexistent.ts"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should extract content when the path has directory structure", () => {
|
||||
const content =
|
||||
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
|
||||
).toBe("const Button = () => <button>Click me</button>;");
|
||||
});
|
||||
|
||||
it("should match exact paths only", () => {
|
||||
const content =
|
||||
"```typescript src/utils.ts\nconst util = {};\n```\n" +
|
||||
"```typescript src/utils/index.ts\nconst index = {};\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
|
||||
"const util = {};",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
|
||||
"const index = {};",
|
||||
);
|
||||
});
|
||||
});
|
||||
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Extracts content from code blocks with given path
|
||||
* @param content The full message content
|
||||
* @param path The file path to look for
|
||||
* @returns The content of the code block if found, undefined otherwise
|
||||
*/
|
||||
export function extractContentFromCodeBlock(
|
||||
content: string,
|
||||
path: string,
|
||||
): string | undefined {
|
||||
// Escape special characters in the path for regex
|
||||
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
// Match the code block with this path
|
||||
// This regex looks for:
|
||||
// 1. Code block start with the path (```[language] path)
|
||||
// 2. The content until the closing ```
|
||||
// The path can be:
|
||||
// - With language: ```typescript src/main.ts
|
||||
// - Without language: ```src/main.ts
|
||||
// - With line ranges: ```js src/main.ts (1-10)
|
||||
const regex = new RegExp(
|
||||
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
|
||||
"m",
|
||||
);
|
||||
|
||||
const match = content.match(regex);
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -37,6 +37,11 @@ export const createRuleBlock: Tool = {
|
|||
description:
|
||||
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
|
||||
},
|
||||
regex: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -7,16 +7,24 @@ export type CreateRuleBlockArgs = Pick<
|
|||
Required<RuleWithSource>,
|
||||
"rule" | "description" | "alwaysApply" | "name"
|
||||
> &
|
||||
Pick<RuleWithSource, "globs">;
|
||||
Pick<RuleWithSource, "globs" | "regex">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
args: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, {
|
||||
// Create options object with the fields that createRuleMarkdown expects
|
||||
const options: any = {
|
||||
description: args.description,
|
||||
globs: args.globs,
|
||||
});
|
||||
};
|
||||
|
||||
// Add regex if provided
|
||||
if (args.regex) {
|
||||
options.regex = args.regex;
|
||||
}
|
||||
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, options);
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark
|
|||
|
||||
- `name` (**required** for YAML): A display name/title for the rule
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`).
|
||||
- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context.
|
||||
- `alwaysApply`: true - Always include the rule, regardless of file context
|
||||
- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
|
||||
|
|
|
|||
|
|
@ -30,14 +30,14 @@ export class AutocompleteActions {
|
|||
expect(ghostText1).to.equal(messagePair1.llmResponse);
|
||||
}
|
||||
|
||||
public static async forceCompletion(editor: TextEditor): Promise<string> {
|
||||
public static async forceCompletion(editor: TextEditor): Promise<string> {
|
||||
await editor.setText("def main():\n ");
|
||||
await editor.moveCursor(2, 5);
|
||||
|
||||
await new Workbench().executeCommand("Continue: Force Autocomplete");
|
||||
|
||||
const ghostText = await TestUtils.waitForSuccess(() =>
|
||||
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver)
|
||||
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver),
|
||||
);
|
||||
|
||||
return ghostText;
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ export function createRuleMarkdown(
|
|||
options: {
|
||||
description?: string;
|
||||
globs?: string | string[];
|
||||
regex?: string | string[];
|
||||
alwaysApply?: boolean;
|
||||
} = {},
|
||||
): string {
|
||||
|
|
@ -44,6 +45,11 @@ export function createRuleMarkdown(
|
|||
typeof options.globs === "string" ? options.globs.trim() : options.globs;
|
||||
}
|
||||
|
||||
if (options.regex) {
|
||||
frontmatter.regex =
|
||||
typeof options.regex === "string" ? options.regex.trim() : options.regex;
|
||||
}
|
||||
|
||||
if (options.description) {
|
||||
frontmatter.description = options.description.trim();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { RuleObject } from "../schemas/index.js";
|
|||
|
||||
export interface RuleFrontmatter {
|
||||
globs?: RuleObject["globs"];
|
||||
regex?: RuleObject["regex"];
|
||||
name?: RuleObject["name"];
|
||||
description?: RuleObject["description"];
|
||||
alwaysApply?: RuleObject["alwaysApply"];
|
||||
|
|
@ -78,6 +79,7 @@ export function markdownToRule(
|
|||
name: getRuleName(frontmatter, id),
|
||||
rule: markdown,
|
||||
globs: frontmatter.globs,
|
||||
regex: frontmatter.regex,
|
||||
description: frontmatter.description,
|
||||
alwaysApply: frontmatter.alwaysApply,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ const ruleObjectSchema = z.object({
|
|||
rule: z.string(),
|
||||
description: z.string().optional(),
|
||||
globs: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
regex: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
alwaysApply: z.boolean().optional(),
|
||||
});
|
||||
const ruleSchema = z.union([z.string(), ruleObjectSchema]);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue