| 1 | import { ConfigValidationError } from "@continuedev/config-yaml"; |
| 2 | import { IDE, RuleWithSource } from "../.."; |
| 3 | import { walkDirs } from "../../indexing/walkDir"; |
| 4 | import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; |
| 5 | |
| 6 | /** |
| 7 | * Gets the directory part of a path (without using Node.js path module) |
| 8 | */ |
| 9 | const getDirname = (filePath: string): string => { |
| 10 | // Normalize path separators to forward slash |
| 11 | const normalizedPath = filePath.replace(/\\/g, "/"); |
| 12 | |
| 13 | // Find the last slash |
| 14 | const lastSlashIndex = normalizedPath.lastIndexOf("/"); |
| 15 | |
| 16 | // If no slash found, return empty string (current directory) |
| 17 | if (lastSlashIndex === -1) { |
| 18 | return ""; |
| 19 | } |
| 20 | |
| 21 | // Return everything up to the last slash |
| 22 | return normalizedPath.substring(0, lastSlashIndex); |
| 23 | }; |
| 24 | |
| 25 | /** |
| 26 | * Loads rules from rules.md files colocated in the codebase |
| 27 | */ |
| 28 | export async function loadCodebaseRules(ide: IDE): Promise<{ |
| 29 | rules: RuleWithSource[]; |
| 30 | errors: ConfigValidationError[]; |
| 31 | }> { |
| 32 | const errors: ConfigValidationError[] = []; |
| 33 | const rules: RuleWithSource[] = []; |
| 34 | |
| 35 | try { |
| 36 | // Get all files from the workspace |
| 37 | const allFiles = await walkDirs(ide); |
| 38 | |
| 39 | // Filter to just rules.md files |
| 40 | const rulesMdFiles = allFiles.filter((file) => { |
| 41 | const parts = file.split("/"); |
| 42 | const filename = parts[parts.length - 1]; |
| 43 | return filename === "rules.md"; |
| 44 | }); |
| 45 | |
| 46 | // Process each rules.md file |
| 47 | for (const filePath of rulesMdFiles) { |
| 48 | try { |
| 49 | const content = await ide.readFile(filePath); |
| 50 | const rule = convertMarkdownRuleToContinueRule(filePath, content); |
| 51 | |
| 52 | rules.push(rule); |
| 53 | } catch (e) { |
| 54 | errors.push({ |
| 55 | fatal: false, |
| 56 | message: `Failed to parse colocated rule file ${filePath}: ${e instanceof Error ? e.message : e}`, |
| 57 | }); |
| 58 | } |
| 59 | } |
| 60 | } catch (e) { |
| 61 | errors.push({ |
| 62 | fatal: false, |
| 63 | message: `Error loading colocated rule files: ${e instanceof Error ? e.message : e}`, |
| 64 | }); |
| 65 | } |
| 66 | |
| 67 | return { rules, errors }; |
| 68 | } |