| 1 | import { ConfigYaml } from "@continuedev/config-yaml"; |
| 2 | import * as YAML from "yaml"; |
| 3 | import { ToolImpl } from "."; |
| 4 | import { joinPathsToUri } from "../../util/uri"; |
| 5 | |
| 6 | export interface CreateRuleBlockArgs { |
| 7 | name: string; |
| 8 | rule: string; |
| 9 | globs?: string; |
| 10 | } |
| 11 | |
| 12 | export const createRuleBlockImpl: ToolImpl = async ( |
| 13 | args: CreateRuleBlockArgs, |
| 14 | extras, |
| 15 | ) => { |
| 16 | // Sanitize rule name for use in filename (remove special chars, replace spaces with dashes) |
| 17 | const safeRuleName = args.name |
| 18 | .toLowerCase() |
| 19 | .replace(/[^a-z0-9\s-]/g, "") |
| 20 | .replace(/\s+/g, "-"); |
| 21 | |
| 22 | const ruleObject = { |
| 23 | name: args.name, |
| 24 | rule: args.rule, |
| 25 | ...(args.globs ? { globs: args.globs.trim() } : {}), |
| 26 | }; |
| 27 | |
| 28 | const ruleBlock: ConfigYaml = { |
| 29 | name: args.name, |
| 30 | version: "0.0.1", |
| 31 | schema: "v1", |
| 32 | rules: [ruleObject], |
| 33 | }; |
| 34 | |
| 35 | const ruleYaml = YAML.stringify(ruleBlock); |
| 36 | |
| 37 | const [localContinueDir] = await extras.ide.getWorkspaceDirs(); |
| 38 | const rulesDirUri = joinPathsToUri( |
| 39 | localContinueDir, |
| 40 | ".continue", |
| 41 | "rules", |
| 42 | `${safeRuleName}.yaml`, |
| 43 | ); |
| 44 | |
| 45 | await extras.ide.writeFile(rulesDirUri, ruleYaml); |
| 46 | await extras.ide.openFile(rulesDirUri); |
| 47 | |
| 48 | return [ |
| 49 | { |
| 50 | name: "New Rule Block", |
| 51 | description: "", // No description throws an error in the GUI |
| 52 | uri: { |
| 53 | type: "file", |
| 54 | value: rulesDirUri, |
| 55 | }, |
| 56 | content: "Rule created successfully", |
| 57 | }, |
| 58 | ]; |
| 59 | }; |