| 1 | import * as YAML from "yaml"; |
| 2 | import { joinPathsToUri } from "../../util/uri"; |
| 3 | import { RuleFrontmatter } from "./parseMarkdownRule"; |
| 4 | |
| 5 | export const RULE_FILE_EXTENSION = "md"; |
| 6 | |
| 7 | /** |
| 8 | * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes) |
| 9 | */ |
| 10 | export function sanitizeRuleName(name: string): string { |
| 11 | return name |
| 12 | .toLowerCase() |
| 13 | .replace(/[^a-z0-9\s-]/g, "") |
| 14 | .replace(/\s+/g, "-") |
| 15 | .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Creates the file path for a rule in the workspace .continue/rules directory |
| 20 | */ |
| 21 | export function createRuleFilePath( |
| 22 | workspaceDir: string, |
| 23 | ruleName: string, |
| 24 | ): string { |
| 25 | const safeRuleName = sanitizeRuleName(ruleName); |
| 26 | return joinPathsToUri( |
| 27 | workspaceDir, |
| 28 | ".continue", |
| 29 | "rules", |
| 30 | `${safeRuleName}.${RULE_FILE_EXTENSION}`, |
| 31 | ); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule |
| 36 | */ |
| 37 | export function createMarkdownWithFrontmatter( |
| 38 | frontmatter: RuleFrontmatter, |
| 39 | markdown: string, |
| 40 | ): string { |
| 41 | const frontmatterStr = YAML.stringify(frontmatter).trim(); |
| 42 | return `---\n${frontmatterStr}\n---\n\n${markdown}`; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Creates a rule markdown file content from rule components |
| 47 | */ |
| 48 | export function createRuleMarkdown( |
| 49 | name: string, |
| 50 | ruleContent: string, |
| 51 | options: { |
| 52 | description?: string; |
| 53 | globs?: string | string[]; |
| 54 | alwaysApply?: boolean; |
| 55 | } = {}, |
| 56 | ): string { |
| 57 | const frontmatter: RuleFrontmatter = {}; |
| 58 | |
| 59 | if (options.globs) { |
| 60 | frontmatter.globs = |
| 61 | typeof options.globs === "string" ? options.globs.trim() : options.globs; |
| 62 | } |
| 63 | |
| 64 | if (options.description) { |
| 65 | frontmatter.description = options.description.trim(); |
| 66 | } |
| 67 | |
| 68 | if (options.alwaysApply !== undefined) { |
| 69 | frontmatter.alwaysApply = options.alwaysApply; |
| 70 | } |
| 71 | |
| 72 | const markdownBody = `# ${name}\n\n${ruleContent}`; |
| 73 | |
| 74 | return createMarkdownWithFrontmatter(frontmatter, markdownBody); |
| 75 | } |