| 1 | import * as YAML from "yaml"; |
| 2 | import { ToolImpl } from "."; |
| 3 | import { RuleWithSource } from "../.."; |
| 4 | import { RuleFrontmatter } from "../../config/markdown/parseMarkdownRule"; |
| 5 | import { joinPathsToUri } from "../../util/uri"; |
| 6 | |
| 7 | export type CreateRuleBlockArgs = Pick< |
| 8 | Required<RuleWithSource>, |
| 9 | "rule" | "description" | "alwaysApply" | "name" |
| 10 | > & |
| 11 | Pick<RuleWithSource, "globs">; |
| 12 | |
| 13 | export const createRuleBlockImpl: ToolImpl = async ( |
| 14 | args: CreateRuleBlockArgs, |
| 15 | extras, |
| 16 | ) => { |
| 17 | // Sanitize rule name for use in filename (remove special chars, replace spaces with dashes) |
| 18 | const safeRuleName = args.name |
| 19 | .toLowerCase() |
| 20 | .replace(/[^a-z0-9\s-]/g, "") |
| 21 | .replace(/\s+/g, "-"); |
| 22 | |
| 23 | const fileExtension = "md"; |
| 24 | |
| 25 | const frontmatter: RuleFrontmatter = {}; |
| 26 | |
| 27 | if (args.globs) { |
| 28 | frontmatter.globs = |
| 29 | typeof args.globs === "string" ? args.globs.trim() : args.globs; |
| 30 | } |
| 31 | |
| 32 | if (args.description) { |
| 33 | frontmatter.description = args.description.trim(); |
| 34 | } |
| 35 | |
| 36 | if (args.alwaysApply !== undefined) { |
| 37 | frontmatter.alwaysApply = args.alwaysApply; |
| 38 | } |
| 39 | |
| 40 | const frontmatterYaml = YAML.stringify(frontmatter).trim(); |
| 41 | let fileContent = `--- |
| 42 | ${frontmatterYaml} |
| 43 | --- |
| 44 | |
| 45 | # ${args.name} |
| 46 | |
| 47 | ${args.rule} |
| 48 | `; |
| 49 | const [localContinueDir] = await extras.ide.getWorkspaceDirs(); |
| 50 | const rulesDirUri = joinPathsToUri( |
| 51 | localContinueDir, |
| 52 | ".continue", |
| 53 | "rules", |
| 54 | `${safeRuleName}.${fileExtension}`, |
| 55 | ); |
| 56 | |
| 57 | await extras.ide.writeFile(rulesDirUri, fileContent); |
| 58 | await extras.ide.openFile(rulesDirUri); |
| 59 | |
| 60 | return [ |
| 61 | { |
| 62 | name: "New Rule Block", |
| 63 | description: args.description || "", |
| 64 | uri: { |
| 65 | type: "file", |
| 66 | value: rulesDirUri, |
| 67 | }, |
| 68 | content: `Rule created successfully`, |
| 69 | }, |
| 70 | ]; |
| 71 | }; |