rop-import.js 2.74 KB
#!/usr/bin/env node
/**
 * ROP 接口一键导入(契约 + adapter + 迁移已有 API)
 *
 * npm run rop:import -- --method dj.api.smartcarlife.pc.abnormalFlowDeclaration.approve
 * npm run rop:import -- --method ... --dry-run
 */
const { runImport, extractMethodFromText } = require("../src/libs/rop/ropImport");

function parseArgs(argv) {
	const args = {};
	for (let i = 2; i < argv.length; i += 1) {
		const key = argv[i];
		if (!key.startsWith("--")) {
			if (!args._text) {
				args._text = key;
			} else {
				args._text += ` ${key}`;
			}
			continue;
		}
		const name = key.slice(2);
		const value = argv[i + 1];
		if (value && !value.startsWith("--")) {
			args[name] = value;
			i += 1;
		} else {
			args[name] = true;
		}
	}
	return args;
}

function printReport(report) {
	console.log("\n=== ROP Import Report ===");
	console.log("Method:", report.method);
	if (report.summary) {
		console.log("Summary:", report.summary);
	}
	console.log("Feature:", report.feature);
	console.log("API file:", report.apiFile);
	if (report.existingFunction) {
		console.log("Migrated function:", report.existingFunction);
	}
	console.log("Request:", report.requestParams.map((p) => `${p.name}${p.required ? "*" : ""}`).join(", "));
	console.log("Response:", report.responseRoot, report.pagination ? "(pagination)" : "");
	console.log("\nFiles:");
	report.files.forEach((item) => {
		console.log(`- ${item.status}: ${item.path}`);
	});
	console.log("\nNext steps:");
	report.nextSteps.forEach((step) => console.log(`- ${step}`));
	if (report.reportPath) {
		console.log("\nReport:", report.reportPath);
	}
}

const USAGE = "Usage: npm run rop:import -- --method <dj.api.smartcarlife.*> "
	+ "[--feature name] [--api finance] [--dry-run] [--force] [--json]";

async function runCli(argv, deps = {}) {
	const runImportFn = deps.runImport || runImport;
	const extractFn = deps.extractMethodFromText || extractMethodFromText;
	const args = parseArgs(argv);
	const method = args.method || extractFn(args._text || "");
	if (!method) {
		const error = new Error(USAGE);
		error.code = "USAGE";
		throw error;
	}

	const report = await runImportFn({
		method,
		feature: args.feature,
		api: args.api,
		dryRun: !!args["dry-run"],
		force: !!args.force,
		swagger: args.swagger,
	});

	return { report, json: !!args.json };
}

async function main() {
	const { report, json } = await runCli(process.argv);
	if (json) {
		console.log(JSON.stringify(report, null, 2));
	} else {
		printReport(report);
	}
}

if (require.main === module) {
	main().catch((error) => {
		console.error("Import failed:", error.message);
		if (error.cause?.message) {
			console.error("Cause:", error.cause.message);
		}
		process.exit(error.code === "USAGE" ? 1 : 1);
	});
}

module.exports = {
	parseArgs,
	printReport,
	runCli,
	USAGE,
};