1
+ import { readFileSync } from "node:fs" ;
2
+
1
3
import { type Edit , Lang , type NapiConfig , parse , type SgNode } from "@ast-grep/napi" ;
2
4
import yaml from "yaml" ;
3
5
@@ -8,7 +10,7 @@ import yaml from "yaml";
8
10
export type RuleConfig = NapiConfig & { fix ?: string } ;
9
11
10
12
/**
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
12
14
*
13
15
* The rule must have a `fix` to rewrite the matched node.
14
16
*
@@ -17,9 +19,9 @@ export type RuleConfig = NapiConfig & { fix?: string };
17
19
* @param rule The rule. Either a yaml string or an instance of `RuleConfig`
18
20
* @param root The root node
19
21
* @param once only apply once
20
- * @returns A list of edits.
22
+ * @returns A list of edits and a list of matches .
21
23
*/
22
- export function getRuleEdits ( rule : string | RuleConfig , root : SgNode , { once = false } = { } ) {
24
+ export function applyRule ( rule : string | RuleConfig , root : SgNode , { once = false } = { } ) {
23
25
const ruleConfig : RuleConfig = typeof rule === "string" ? yaml . parse ( rule ) : rule ;
24
26
if ( ruleConfig . transform ) {
25
27
throw new Error ( "transform is not supported" ) ;
@@ -50,7 +52,18 @@ export function getRuleEdits(rule: string | RuleConfig, root: SgNode, { once = f
50
52
) ;
51
53
} ) ;
52
54
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 ( ) ;
54
67
}
55
68
56
69
/**
@@ -71,6 +84,6 @@ export function patchCode(
71
84
{ lang = Lang . TypeScript , once = false } = { }
72
85
) : string {
73
86
const node = parse ( lang , code ) . root ( ) ;
74
- const edits = getRuleEdits ( rule , node , { once } ) ;
87
+ const { edits } = applyRule ( rule , node , { once } ) ;
75
88
return node . commitEdits ( edits ) ;
76
89
}
0 commit comments