agentlens / src /cli /commands /move.ts
hongcoding's picture
feat: DSH bot-instruction parser + dedupe + DSH panel project picker
0fc6e34 verified
Raw History Blame Contribute Delete
2.89 kB
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import type { Rule, AgentKind } from "../../core/types.js";
import { parsers } from "../../parsers/index.js";
import { generateConfig, outputFileFor } from "../../migrator/generate.js";
import { dedupeRules } from "../../core/dedupe.js";
import { findAgentFiles } from "../../core/files.js";
interface MoveOpts {
from: string;
to: string;
path: string;
output?: string;
}
/** Find all config files for a given agent in the project. */
/** Parse all rules from source agent files. */
function parseRules(root: string, agent: string): Rule[] {
const parser = parsers[agent];
if (!parser) throw new Error(`Unknown agent: ${agent}. Supported: ${Object.keys(parsers).join(", ")}`);
const files = findAgentFiles(root, agent);
const rules: Rule[] = [];
for (const file of files) {
const content = readFileSync(file, "utf-8");
rules.push(...parser.parse(content, file));
}
return rules;
}
export async function moveRules(opts: MoveOpts): Promise<void> {
const root = resolve(opts.path);
const fromAgent = opts.from as AgentKind;
const toAgent = opts.to as AgentKind;
console.log(`Migrating rules: ${opts.from} → ${opts.to}\n`);
// Parse source rules (dedupe: an agent may expose several rule sources)
const rules = dedupeRules(parseRules(root, opts.from));
if (rules.length === 0) {
console.log(`⚠ No rules found for agent "${opts.from}" in ${root}`);
const files = findAgentFiles(root, opts.from);
if (files.length === 0) {
console.log(` No config files found. Looked for: ${parsers[opts.from]?.filePatterns.join(", ")}`);
}
return;
}
console.log(` Found ${rules.length} rules from ${rules.length > 0 ? rules[0].source.file : "?"}\n`);
// Generate target format
const output = generateConfig(rules, toAgent);
const outputPath = opts.output
? resolve(root, opts.output)
: resolve(root, outputFileFor(toAgent));
// Write output
mkdirSync(dirname(outputPath), { recursive: true });
writeFileSync(outputPath, output, "utf-8");
console.log(` ✅ Generated ${outputPath}`);
// True same-file case: the rules were read from the very file we just wrote.
const sourceFile = rules[0]?.source.file;
const sameFile = sourceFile !== undefined && resolve(sourceFile) === outputPath;
if (sameFile) {
console.log(` ${opts.from} 和 ${opts.to} 使用同一个规则文件 ${outputFileFor(toAgent)}——迁移会原地整理(幂等,不重复添加规则)\n`);
} else {
console.log(` ${rules.length} rules converted from ${opts.from} format to ${opts.to} format\n`);
}
// Show preview
const preview = output.split("\n").slice(0, 15).join("\n");
console.log(` Preview:\n ${preview.split("\n").join("\n ")}`);
}