1+ import { readFileSync } from "node:fs" ;
2+
13import { type Edit , Lang , type NapiConfig , parse , type SgNode } from "@ast-grep/napi" ;
24import yaml from "yaml" ;
35
@@ -8,7 +10,7 @@ import yaml from "yaml";
810export type RuleConfig = NapiConfig & { fix ?: string } ;
911
1012/**
11- * Returns the `Edit`s for an ast-grep rule in yaml format
13+ * Returns the `Edit`s and `Match`es for an ast-grep rule in yaml format
1214 *
1315 * The rule must have a `fix` to rewrite the matched node.
1416 *
@@ -17,9 +19,9 @@ export type RuleConfig = NapiConfig & { fix?: string };
1719 * @param rule The rule. Either a yaml string or an instance of `RuleConfig`
1820 * @param root The root node
1921 * @param once only apply once
20- * @returns A list of edits.
22+ * @returns A list of edits and a list of matches .
2123 */
22- export function getRuleEdits ( rule : string | RuleConfig , root : SgNode , { once = false } = { } ) {
24+ export function applyRule ( rule : string | RuleConfig , root : SgNode , { once = false } = { } ) {
2325 const ruleConfig : RuleConfig = typeof rule === "string" ? yaml . parse ( rule ) : rule ;
2426 if ( ruleConfig . transform ) {
2527 throw new Error ( "transform is not supported" ) ;
@@ -50,7 +52,18 @@ export function getRuleEdits(rule: string | RuleConfig, root: SgNode, { once = f
5052 ) ;
5153 } ) ;
5254
53- return edits ;
55+ return { edits, matches } ;
56+ }
57+
58+ /**
59+ * Parse a file and obtain its root.
60+ *
61+ * @param path The file path
62+ * @param lang The language to parse. Defaults to TypeScript.
63+ * @returns The root for the file.
64+ */
65+ export function parseFile ( path : string , lang = Lang . TypeScript ) {
66+ return parse ( lang , readFileSync ( path , { encoding : "utf-8" } ) ) . root ( ) ;
5467}
5568
5669/**
@@ -71,6 +84,6 @@ export function patchCode(
7184 { lang = Lang . TypeScript , once = false } = { }
7285) : string {
7386 const node = parse ( lang , code ) . root ( ) ;
74- const edits = getRuleEdits ( rule , node , { once } ) ;
87+ const { edits } = applyRule ( rule , node , { once } ) ;
7588 return node . commitEdits ( edits ) ;
7689}
0 commit comments