-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathcreate-xpath-custom-rule.ts
More file actions
215 lines (189 loc) · 6.93 KB
/
create-xpath-custom-rule.ts
File metadata and controls
215 lines (189 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import path from "node:path";
import fs from "node:fs/promises";
import { escapeXml, toSafeFilenameSlug } from "../utils.js";
// Creates PMD XPath ruleset XML and updates code-analyzer.yml.
export type CreateXpathCustomRuleInput = {
xpath: string;
ruleName?: string;
description?: string;
language?: string;
engine?: string;
priority?: number;
workingDirectory?: string;
};
export type CreateXpathCustomRuleOutput = {
status: string;
ruleXml?: string;
rulesetPath?: string;
configPath?: string;
};
export interface CreateXpathCustomRuleAction {
exec(input: CreateXpathCustomRuleInput): Promise<CreateXpathCustomRuleOutput>;
}
export class CreateXpathCustomRuleActionImpl implements CreateXpathCustomRuleAction {
public async exec(input: CreateXpathCustomRuleInput): Promise<CreateXpathCustomRuleOutput> {
const normalized = normalizeInput(input);
if ("error" in normalized) {
return { status: normalized.error };
}
const ruleXml = await buildRuleXml(normalized);
const { customRulesDir, rulesetPath, configPath } = buildPaths(normalized);
const rulesetPathForConfig = toRelativeRulesetPath(normalized.workingDirectory, rulesetPath);
await fs.mkdir(customRulesDir, { recursive: true });
await fs.writeFile(rulesetPath, ruleXml, "utf8");
await upsertCodeAnalyzerConfig(configPath, rulesetPathForConfig, normalized.engine);
return { status: "success", ruleXml, rulesetPath, configPath };
}
}
type NormalizedInput = {
xpath: string;
engine: string;
ruleName: string;
description: string;
language: string;
priority: number;
workingDirectory: string;
};
const DEFAULT_RULE_NAME = "CustomXPathRule";
const DEFAULT_DESCRIPTION = "Generated rule from XPath";
const DEFAULT_LANGUAGE = "apex";
const DEFAULT_PRIORITY = 3;
const CUSTOM_RULES_DIR_NAME = "custom-rules";
function normalizeInput(input: CreateXpathCustomRuleInput): NormalizedInput | { error: string } {
const xpath = (input.xpath ?? "").trim();
if (!xpath) {
return { error: "xpath is required" };
}
const engine = (input.engine ?? "pmd").toLowerCase();
if (engine !== "pmd") {
return { error: `engine '${engine}' is not supported yet` };
}
const workingDirectory = input.workingDirectory?.trim();
if (!workingDirectory) {
return { error: "workingDirectory is required" };
}
return {
xpath,
engine,
ruleName: input.ruleName?.trim() || DEFAULT_RULE_NAME,
description: input.description?.trim() || DEFAULT_DESCRIPTION,
language: (input.language ?? DEFAULT_LANGUAGE).toLowerCase(),
priority: Number.isFinite(input.priority) ? (input.priority as number) : DEFAULT_PRIORITY,
workingDirectory
};
}
async function buildRuleXml(input: NormalizedInput): Promise<string> {
const templatePath = new URL("../templates/pmd-ruleset.xml", import.meta.url);
const template = await fs.readFile(templatePath, "utf8");
return applyTemplate(template, {
rulesetName: escapeXml(input.ruleName),
rulesetDescription: escapeXml(input.description),
ruleName: escapeXml(input.ruleName),
language: escapeXml(input.language),
ruleMessage: escapeXml(input.description),
ruleDescription: escapeXml(input.description),
documentationUrl: "",
priority: String(input.priority),
xpathExpression: input.xpath,
exampleCode: ""
});
}
function buildPaths(input: NormalizedInput): { customRulesDir: string; rulesetPath: string; configPath: string } {
const customRulesDir = path.join(input.workingDirectory, CUSTOM_RULES_DIR_NAME);
const safeRuleName = toSafeFilenameSlug(input.ruleName);
return {
customRulesDir,
rulesetPath: path.join(customRulesDir, `${safeRuleName}-${input.engine}-rules.xml`),
configPath: path.join(input.workingDirectory, "code-analyzer.yml")
};
}
function toRelativeRulesetPath(workingDirectory: string, rulesetPath: string): string {
const relativePath = path.relative(workingDirectory, rulesetPath);
if (path.isAbsolute(relativePath) || relativePath.startsWith("..")) {
throw new Error("Ruleset path must remain within the workingDirectory.");
}
return relativePath.split(path.sep).join("/");
}
function applyTemplate(template: string, values: Record<string, string>): string {
return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => values[key] ?? "");
}
async function upsertCodeAnalyzerConfig(configPath: string, rulesetPath: string, engine: string): Promise<void> {
const existing = await readConfigIfExists(configPath);
if (!existing) {
await writeNewCodeAnalyzerConfig(configPath, rulesetPath, engine);
return;
}
if (existing.includes(rulesetPath)) {
return;
}
const updated = addRulesetPath(existing, rulesetPath, engine);
await fs.writeFile(configPath, updated, "utf8");
}
function addRulesetPath(configContent: string, rulesetPath: string, engine: string): string {
const lines = configContent.split(/\r?\n/);
const indices = findRulesetBlockIndices(lines, engine);
if (indices.customRulesetsLineIndex !== -1) {
lines.splice(indices.customRulesetsLineIndex + 1, 0, ` - "${rulesetPath}"`);
return lines.join("\n");
}
if (indices.engineLineIndex !== -1) {
lines.splice(indices.engineLineIndex + 1, 0, " custom_rulesets:", ` - "${rulesetPath}"`);
return lines.join("\n");
}
return appendEngineRulesetBlock(configContent, rulesetPath, engine);
}
async function readConfigIfExists(configPath: string): Promise<string | null> {
try {
return await fs.readFile(configPath, "utf8");
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
return null;
}
throw error;
}
}
async function writeNewCodeAnalyzerConfig(
configPath: string,
rulesetPath: string,
engine: string
): Promise<void> {
const templatePath = new URL("../templates/code-analyzer.yml", import.meta.url);
const template = await fs.readFile(templatePath, "utf8");
const content = applyTemplate(template, { rulesetPath, engine });
await fs.writeFile(configPath, content, "utf8");
}
function findRulesetBlockIndices(
lines: string[],
engine: string
): { enginesLineIndex: number; engineLineIndex: number; customRulesetsLineIndex: number } {
let enginesLineIndex = -1;
let engineLineIndex = -1;
let customRulesetsLineIndex = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (trimmed === "engines:") {
enginesLineIndex = i;
continue;
}
if (trimmed === `${engine}:` && enginesLineIndex !== -1) {
engineLineIndex = i;
continue;
}
if (trimmed === "custom_rulesets:" && engineLineIndex !== -1) {
customRulesetsLineIndex = i;
break;
}
}
return { enginesLineIndex, engineLineIndex, customRulesetsLineIndex };
}
function appendEngineRulesetBlock(configContent: string, rulesetPath: string, engine: string): string {
return [
configContent.trimEnd(),
"",
"engines:",
` ${engine}:`,
" custom_rulesets:",
` - "${rulesetPath}"`
].join("\n");
}