-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfile-tool.ts
More file actions
416 lines (374 loc) · 12.6 KB
/
file-tool.ts
File metadata and controls
416 lines (374 loc) · 12.6 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* File tool factory — creates codebase check/fix tools from declarative configs.
*
* Each tool is a pure function that receives file data and returns issues or mutations.
* The factory generates: validator adapter, CLI handler, and library function.
*
* Supports two modes:
* - Per-file (`checkFile`): factory auto-iterates over files
* - Batch (`checkAll`): tool receives full file list
*
* Fixers return Edit-tool-shaped mutations `{path, oldContent, newContent}` —
* the runner decides whether to apply, preview, or pass to an AI agent.
*
* ```
* Pure logic (Handler) Runner (Adapter) Output (ResponseMapper)
* ───────────────────── ────────────────── ─────────────────────────
* checkFile() → issues[] CLI runner Terminal colors + exit code
* fixFile() → mutation MCP server (IDE tool) JSON tool results
* AI agent (SDK tool) Structured for LLM
* ```
*
* @module
*/
import * as cliParseArgs from "@std/cli/parse-args";
import * as primitives from "@eserstack/primitives";
import * as functions from "@eserstack/functions";
import type * as shellArgs from "@eserstack/shell/args";
import * as tui from "@eserstack/shell/tui";
import type {
StackId,
Validator,
ValidatorResult,
} from "./validation/types.ts";
import {
type FileEntry,
type FileMutation,
loadContent,
type WalkOptions,
walkSourceFiles,
} from "./file-tools-shared.ts";
import { createCliContext, toCliEvent } from "./cli-support.ts";
import { ensureLib, getLib } from "./ffi-client.ts";
const { ctx, output: _out } = createCliContext();
// =============================================================================
// Types
// =============================================================================
/**
* A single issue found by a tool.
*/
export type ToolIssue = {
/** File path */
readonly path: string;
/** Line number (if applicable) */
readonly line?: number;
/** Issue description */
readonly message: string;
/** Whether this was auto-fixed */
readonly fixed?: boolean;
};
/**
* Result of running a file tool.
*/
export type ToolResult = {
/** Tool name */
readonly name: string;
/** Issues found */
readonly issues: readonly ToolIssue[];
/** Mutations to apply (fixers only) */
readonly mutations: readonly FileMutation[];
/** Number of files checked */
readonly filesChecked: number;
};
/**
* Options passed to tool check/fix functions.
* Merged from: defaults → .eser/manifest.yml → CLI flags.
*/
export type ToolOptions = {
readonly root: string;
readonly fix: boolean;
readonly exclude: readonly (string | RegExp)[];
readonly [key: string]: unknown;
};
/**
* Declarative configuration for creating a file tool.
*/
export type FileToolConfig = {
/** Unique tool name (used as CLI command and validator name) */
readonly name: string;
/** Human-readable description */
readonly description: string;
/** Whether this tool can fix issues */
readonly canFix: boolean;
/** Required stacks (empty = all) */
readonly stacks: readonly StackId[];
/** Default option values */
readonly defaults: Record<string, unknown>;
/** File extensions to scan (empty = all) */
readonly extensions?: readonly string[];
/** Per-file check — factory auto-iterates */
readonly checkFile?: (
file: FileEntry,
content: string | undefined,
options: ToolOptions,
) => ToolIssue[];
/** Batch check — receives all files */
readonly checkAll?: (
files: readonly FileEntry[],
options: ToolOptions,
) => ToolIssue[] | Promise<ToolIssue[]>;
/** Per-file fix — returns a mutation or undefined */
readonly fixFile?: (
file: FileEntry,
content: string,
options: ToolOptions,
) => FileMutation | undefined;
};
/**
* A created file tool with all adapters.
*/
export type FileTool = {
/** Tool configuration */
readonly config: FileToolConfig;
/** Run the tool programmatically */
readonly run: (options?: Partial<ToolOptions>) => Promise<ToolResult>;
/** Validator adapter for the validation system */
readonly validator: Validator;
/** CLI entry point */
readonly main: (
cliArgs?: readonly string[],
) => Promise<shellArgs.CliResult<void>>;
};
// =============================================================================
// Factory
// =============================================================================
/**
* Create a file tool from a declarative config.
*
* @param config - Tool configuration
* @returns A complete file tool with run(), validator, and main()
*/
export const createFileTool = (config: FileToolConfig): FileTool => {
// --- Core run function ---
const run = async (
partialOptions?: Partial<ToolOptions>,
): Promise<ToolResult> => {
const options: ToolOptions = {
root: partialOptions?.root ?? ".",
fix: partialOptions?.fix ?? false,
exclude: partialOptions?.exclude ?? [],
...config.defaults,
...partialOptions,
};
const changedFiles = partialOptions?.["_changedFiles"] as
| string[]
| undefined;
const walkOpts: WalkOptions = {
root: options.root,
extensions: config.extensions,
exclude: options.exclude,
includeOnly: changedFiles !== undefined && changedFiles.length > 0
? changedFiles
: undefined,
};
const files = await walkSourceFiles(walkOpts);
const allIssues: ToolIssue[] = [];
const allMutations: FileMutation[] = [];
if (config.checkAll !== undefined) {
// Batch mode
const issues = await config.checkAll(files, options);
allIssues.push(...issues);
} else if (config.checkFile !== undefined) {
// Per-file mode
for (const file of files) {
const content = await loadContent(file);
const issues = config.checkFile(file, content, options);
allIssues.push(...issues);
}
}
// Run fixer if fix mode is enabled
if (options.fix && config.canFix && config.fixFile !== undefined) {
for (const file of files) {
const content = await loadContent(file);
if (content === undefined) {
continue;
}
const mutation = config.fixFile(file, content, options);
if (mutation !== undefined) {
allMutations.push(mutation);
}
}
}
return {
name: config.name,
issues: allIssues,
mutations: allMutations,
filesChecked: files.length,
};
};
// --- Validator adapter ---
const validator: Validator = {
name: config.name,
description: config.description,
requiredStacks: config.stacks,
async validate(validatorOptions): Promise<ValidatorResult> {
const fix = validatorOptions.options?.["fix"] as boolean | undefined;
const configOptions = validatorOptions.options ?? {};
const result = await run({
root: validatorOptions.root,
fix: fix ?? false,
exclude: [],
...configOptions,
});
return {
name: config.name,
passed: result.issues.length === 0,
issues: result.issues.map((issue) => ({
severity: "error" as const,
message: `${issue.message}${issue.fixed ? " (fixed)" : ""}`,
file: issue.path,
line: issue.line,
})),
stats: {
filesChecked: result.filesChecked,
issuesFound: result.issues.length,
fixedCount: result.mutations.length,
},
};
},
};
// --- CLI adapter ---
const handleCli = async (
event: functions.triggers.CliEvent,
): Promise<shellArgs.CliResult<void>> => {
const fix = config.canFix && event.flags["fix"] === true;
const root = (event.flags["root"] as string | undefined) ?? ".";
const excludeFlag = event.flags["exclude"];
const exclude = excludeFlag !== undefined
? (Array.isArray(excludeFlag)
? excludeFlag as string[]
: [excludeFlag as string])
: [];
try {
const result = await run({ root, fix, exclude });
if (result.mutations.length > 0) {
// Import writeMutations lazily to avoid circular deps
const { writeMutations } = await import("./file-tools-shared.ts");
const written = await writeMutations(result.mutations);
tui.log.success(
ctx,
`Fixed ${written} file(s) for ${config.name}.`,
);
}
if (result.issues.length === 0 && result.mutations.length === 0) {
tui.log.success(
ctx,
`${config.name}: ${result.filesChecked} files checked, no issues.`,
);
return primitives.results.ok(undefined);
}
const unfixed = result.issues.filter((i) => !i.fixed);
if (unfixed.length > 0) {
for (const issue of unfixed) {
const loc = issue.line !== undefined
? `${issue.path}:${issue.line}`
: issue.path;
tui.log.error(ctx, `${loc}: ${issue.message}`);
}
return primitives.results.fail({ exitCode: 1 });
}
return primitives.results.ok(undefined);
} catch (error) {
tui.log.error(
ctx,
error instanceof Error ? error.message : String(error),
);
return primitives.results.fail({ exitCode: 1 });
}
};
// --- CLI main ---
const main = async (
cliArgs?: readonly string[],
): Promise<shellArgs.CliResult<void>> => {
const flags = config.canFix ? ["fix"] : [];
const parsed = cliParseArgs.parseArgs(
(cliArgs ?? []) as string[],
{
boolean: [...flags, "help"],
string: ["root", "exclude"],
alias: { h: "help" },
},
);
if (parsed["help"]) {
console.log(`eser codebase ${config.name} — ${config.description}\n`);
console.log(`Usage: eser codebase ${config.name} [options]\n`);
console.log("Options:");
if (config.canFix) {
console.log(" --fix Auto-fix issues");
}
console.log(" --root <dir> Root directory (default: .)");
console.log(" --exclude <p> Exclude pattern");
console.log(" -h, --help Show this help");
return primitives.results.ok(undefined);
}
const event = toCliEvent(config.name, parsed);
return await handleCli(event);
};
return { config, run, validator, main };
};
/**
* Wraps a FileTool so its registry-facing `validator.validate` delegates to Go's
* built-in file validators when the native FFI library is available.
*
* `run` and `main` are left unchanged so that `--fix` mode still works through
* the TypeScript path (Go validators are check-only).
*
* @param tool - The original FileTool created by `createFileTool`
* @param goValidatorName - The short name used by the Go bridge
* (`"eof"`, `"bom"`, `"trailing"`, `"line-endings"`, `"merge-conflicts"`, `"secrets"`)
*/
export const withGoValidator = (
tool: FileTool,
goValidatorName: string,
): FileTool => {
// Pre-compute dot-prefixed extensions from the tool config (e.g. "ts" → ".ts").
// Passed to Go so the walker only reads relevant files — saves I/O.
const goExtensions = tool.config.extensions !== undefined
? [...tool.config.extensions.map((e) => `.${e}`)]
: undefined;
const goValidator: Validator = {
...tool.validator,
validate: async (options): Promise<ValidatorResult> => {
await ensureLib();
const lib = getLib();
if (lib === null) {
throw new Error(
`FFI library unavailable — cannot run validator "${goValidatorName}"`,
);
}
const raw = lib.symbols.EserAjanCodebaseValidateFiles(
JSON.stringify({
dir: options.root,
validators: [goValidatorName],
extensions: goExtensions,
validatorOptions: { [goValidatorName]: options },
gitAware: true,
}),
);
const parsed = JSON.parse(raw) as {
results?: ValidatorResult[];
error?: string;
};
if (parsed.error) {
throw new Error(
`Go validator "${goValidatorName}" error: ${parsed.error}`,
);
}
if (!parsed.results?.length) {
throw new Error(
`Go validator "${goValidatorName}" returned no results`,
);
}
return { ...parsed.results[0]!, name: tool.validator.name } as ValidatorResult;
},
};
return { ...tool, validator: goValidator };
};
// Re-export types for tool implementations
export type {
FileEntry,
FileMutation,
WalkOptions,
} from "./file-tools-shared.ts";
export { loadBytes, loadContent } from "./file-tools-shared.ts";