Commit ec6361ed by 张立顺

feat: 增加迁移前置门禁

1 parent d3402784
# 迁移门禁
跨项目迁移或较大重构开始前,必须创建迁移 manifest 并通过 `npm run check:migration -- --manifest <manifest> --phase pre`。完成后使用 `--phase post` 复核测试状态和未阻塞验证命令。
小型修复不强制使用该门禁。文档和测试的准备工作可以直接进行,不受门禁阻挡;门禁用于阻止尚未具备迁移证据的业务变更进入迁移阶段。
# API 清单
| 接口 | 调用方 | 来源证据 | 迁移处理 |
| --- | --- | --- | --- |
| `POST /api/order/create` | 订单创建页 | 源项目订单创建流程 | 在目标项目完成鉴权、请求参数与响应映射核对后接入 |
清单中的每一项都应在实际迁移清单中替换为对应接口和可追溯证据。
{
"id": "order-api-migration-example",
"title": "订单接口迁移示例",
"sourceProject": "dj-car-boutique-work-wechat",
"affectedPaths": [
"app.js"
],
"interfaces": [
"POST /api/order/create"
],
"tests": [
{
"id": "migration-readiness-contract",
"file": "tests/migration-readiness/checkMigrationReadiness.test.mjs",
"level": "contract",
"expectedBefore": "pass",
"status": "pass"
}
],
"baseline": {
"command": "git rev-parse --short HEAD",
"result": "d340278"
},
"apiInventory": "docs/migrations/template/api-inventory.md",
"acceptance": "docs/migrations/template/test-acceptance.md",
"verification": {
"commands": [
{
"command": "node --test tests/migration-readiness/checkMigrationReadiness.test.mjs tests/migration-readiness/uploadExclusions.test.mjs",
"status": "pass"
}
]
}
}
# 测试验收
1. 在迁移开始前运行 `npm run check:migration -- --manifest <manifest> --phase pre`。
2. 记录基线命令及其结果,并确认受影响路径、接口清单和测试证据齐全。
3. 迁移完成后将每个测试标为 `pass` 或带有明确原因的 `blocked`。
4. 运行 `npm run check:migration -- --manifest <manifest> --phase post`,由门禁执行未阻塞的验证命令。
5. 将门禁结果与实际测试输出一起保留在迁移记录中。
......@@ -36,6 +36,7 @@
"test:orderLifecycle:e2e": "node scripts/run-node-tests.mjs tests/order-lifecycle/e2e/orderLifecycle.live.test.mjs",
"test:orderLifecycle:ui": "node scripts/run-node-tests.mjs tests/order-lifecycle/ui/miniProgramSmoke.live.test.mjs",
"check:workOrderClosure": "node scripts/check-work-order-migration.mjs",
"check:migration": "node scripts/check-migration-readiness.mjs",
"test:workOrder": "npm run test:workOrderMigration && npm run test:createOrder && npm run test:orderLifecycle && npm run check:workOrderClosure"
}
}
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const realProjectRoot = realpathSync(projectRoot);
const placeholderPattern = /\b(?:TODO|TBD)\b|待补充/i;
function usage() {
console.error('Usage: node scripts/check-migration-readiness.mjs --manifest <path> --phase pre|post');
}
function parseArguments(argumentsList) {
if (argumentsList.length !== 4 || argumentsList[0] !== '--manifest' || argumentsList[2] !== '--phase' || !['pre', 'post'].includes(argumentsList[3])) {
usage();
process.exit(2);
}
return { manifest: argumentsList[1], phase: argumentsList[3] };
}
function isInsideProject(candidate) {
const relative = path.relative(realProjectRoot, candidate);
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
}
function fail(errors) {
for (const error of errors) console.error(`Migration readiness error: ${error}`);
process.exit(1);
}
function requireText(value, name, errors) {
if (typeof value !== 'string' || !value.trim()) errors.push(`${name} is required`);
}
function requireArray(value, name, errors) {
if (!Array.isArray(value) || value.length === 0) errors.push(`${name} must be a non-empty array`);
}
function resolveProjectFile(value, name, errors) {
if (typeof value !== 'string' || !value.trim()) {
errors.push(`${name} must be a non-empty relative path`);
return null;
}
if (path.isAbsolute(value)) {
errors.push(`${name} must be relative to the repository`);
return null;
}
const candidate = path.resolve(projectRoot, value);
if (!isInsideProject(candidate)) {
errors.push(`${name} must stay inside the repository`);
return null;
}
if (!existsSync(candidate)) {
errors.push(`${name} does not exist: ${value}`);
return null;
}
const realCandidate = realpathSync(candidate);
if (!isInsideProject(realCandidate)) {
errors.push(`${name} resolves outside the repository`);
return null;
}
return realCandidate;
}
function checkPlaceholder(file, name, errors) {
if (file && placeholderPattern.test(readFileSync(file, 'utf8'))) errors.push(`${name} contains a placeholder`);
}
function validateManifest(manifest, phase) {
const errors = [];
for (const name of ['id', 'title', 'sourceProject']) requireText(manifest[name], name, errors);
for (const name of ['affectedPaths', 'interfaces', 'tests']) requireArray(manifest[name], name, errors);
if (!manifest.baseline || typeof manifest.baseline !== 'object' || Array.isArray(manifest.baseline)) {
errors.push('baseline is required');
} else {
requireText(manifest.baseline.command, 'baseline.command', errors);
requireText(manifest.baseline.result, 'baseline.result', errors);
}
const inventoryFile = resolveProjectFile(manifest.apiInventory, 'apiInventory', errors);
const acceptanceFile = resolveProjectFile(manifest.acceptance, 'acceptance', errors);
checkPlaceholder(inventoryFile, 'apiInventory', errors);
checkPlaceholder(acceptanceFile, 'acceptance', errors);
for (const [index, affectedPath] of (manifest.affectedPaths || []).entries()) {
resolveProjectFile(affectedPath, `affectedPaths[${index}]`, errors);
}
for (const [index, testCase] of (manifest.tests || []).entries()) {
const prefix = `tests[${index}]`;
if (!testCase || typeof testCase !== 'object' || Array.isArray(testCase)) {
errors.push(`${prefix} must be an object`);
continue;
}
requireText(testCase.id, `${prefix}.id`, errors);
requireText(testCase.level, `${prefix}.level`, errors);
if (!['pass', 'fail'].includes(testCase.expectedBefore)) errors.push(`${prefix}.expectedBefore must be pass or fail`);
resolveProjectFile(testCase.file, `${prefix}.file`, errors);
if (phase === 'post') {
if (testCase.expectedBefore !== 'pass') errors.push(`${prefix} must not remain fail in post phase`);
if (!['pass', 'blocked'].includes(testCase.status)) errors.push(`${prefix}.status must be pass or blocked in post phase`);
if (testCase.status === 'blocked') requireText(testCase.blocker, `${prefix}.blocker`, errors);
}
}
if (placeholderPattern.test(JSON.stringify(manifest))) errors.push('manifest JSON contains a placeholder');
return errors;
}
function checkVerificationCommands(verification, errors) {
if (verification === undefined) return [];
if (!verification || typeof verification !== 'object' || !Array.isArray(verification.commands)) {
errors.push('verification.commands must be an array when verification is provided');
return [];
}
return verification.commands.map((entry, index) => {
const command = typeof entry === 'string' ? entry : entry?.command;
const status = typeof entry === 'string' ? 'pass' : entry?.status;
const blocker = typeof entry === 'string' ? undefined : entry?.blocker;
if (typeof command !== 'string' || !command.trim()) errors.push(`verification.commands[${index}].command is required`);
if (!['pass', 'blocked'].includes(status)) errors.push(`verification.commands[${index}].status must be pass or blocked`);
if (status === 'blocked') requireText(blocker, `verification.commands[${index}].blocker`, errors);
if (/(?:^|\s)(?:\.\.[\\/]|[A-Za-z]:[\\/]|[\\/]{1,2})/.test(command || '')) errors.push(`verification.commands[${index}] points outside the repository`);
return { command, status };
});
}
function main() {
const { manifest: manifestArgument, phase } = parseArguments(process.argv.slice(2));
const manifestPath = path.resolve(process.cwd(), manifestArgument);
if (!existsSync(manifestPath) || !isInsideProject(manifestPath)) fail(['manifest must exist inside the repository']);
const realManifestPath = realpathSync(manifestPath);
if (!isInsideProject(realManifestPath)) fail(['manifest resolves outside the repository']);
let manifest;
try {
manifest = JSON.parse(readFileSync(realManifestPath, 'utf8'));
} catch (error) {
fail([`manifest must be valid JSON: ${error.message}`]);
}
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) fail(['manifest must be a JSON object']);
const errors = validateManifest(manifest, phase);
const commands = phase === 'post' ? checkVerificationCommands(manifest.verification, errors) : [];
if (errors.length > 0) fail(errors);
if (phase === 'post') {
for (const { command, status } of commands) {
if (status === 'blocked') continue;
try {
execSync(command, { cwd: projectRoot, stdio: 'pipe', shell: true });
} catch {
fail([`verification command failed: ${command}`]);
}
}
}
console.log(`Migration readiness ${phase} check passed: ${path.relative(projectRoot, realManifestPath)}`);
}
main();
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const script = path.join(projectRoot, 'scripts/check-migration-readiness.mjs');
function createFixture(options = {}) {
const fixtureRoot = mkdtempSync(path.join(projectRoot, '.migration-readiness-'));
mkdirSync(path.join(fixtureRoot, 'docs'), { recursive: true });
mkdirSync(path.join(fixtureRoot, 'tests'), { recursive: true });
writeFileSync(path.join(fixtureRoot, 'docs/api-inventory.md'), 'API inventory');
writeFileSync(path.join(fixtureRoot, 'docs/acceptance.md'), 'Acceptance criteria');
writeFileSync(path.join(fixtureRoot, 'tests/migration.test.mjs'), 'export {};');
const fixturePath = path.relative(projectRoot, fixtureRoot).replaceAll('\\', '/');
const manifest = {
id: 'order-migration',
title: 'Order migration',
sourceProject: 'source-mini-program',
affectedPaths: ['app.js'],
interfaces: ['Order.create'],
tests: [{ id: 'migration-contract', file: `${fixturePath}/tests/migration.test.mjs`, level: 'contract', expectedBefore: 'pass' }],
baseline: { command: 'git status --short', result: 'clean' },
apiInventory: `${fixturePath}/docs/api-inventory.md`,
acceptance: `${fixturePath}/docs/acceptance.md`,
verification: { commands: ['node --version'] },
...options,
};
const manifestPath = path.join(fixtureRoot, 'manifest.json');
writeFileSync(manifestPath, JSON.stringify(manifest));
return { fixtureRoot, manifestPath };
}
function run(manifestPath, phase) {
try {
return { status: 0, output: execFileSync(process.execPath, [script, '--manifest', manifestPath, '--phase', phase], { encoding: 'utf8' }) };
} catch (error) {
return { status: error.status, output: `${error.stdout || ''}${error.stderr || ''}` };
}
}
function withFixture(options, assertion) {
const fixture = createFixture(options);
try {
assertion(fixture);
} finally {
rmSync(fixture.fixtureRoot, { recursive: true, force: true });
}
}
test('pre phase accepts a complete manifest with repository-local evidence', () => {
withFixture({}, ({ manifestPath }) => {
assert.equal(run(manifestPath, 'pre').status, 0);
});
});
test('pre phase rejects missing migration material and placeholder content', () => {
withFixture({ acceptance: 'docs/missing.md' }, ({ manifestPath }) => {
assert.equal(run(manifestPath, 'pre').status, 1);
});
withFixture({}, ({ fixtureRoot, manifestPath }) => {
writeFileSync(path.join(fixtureRoot, 'docs/api-inventory.md'), 'TODO: inventory');
assert.equal(run(manifestPath, 'pre').status, 1);
});
});
test('pre phase rejects missing test evidence and paths outside the repository', () => {
withFixture({ tests: [{ id: 'missing-test', file: '.migration-readiness-missing/tests/missing.test.mjs', level: 'unit', expectedBefore: 'pass' }] }, ({ manifestPath }) => {
assert.equal(run(manifestPath, 'pre').status, 1);
});
withFixture({ apiInventory: '../outside.md' }, ({ manifestPath }) => {
assert.equal(run(manifestPath, 'pre').status, 1);
});
});
test('post phase requires successful or explicitly blocked tests', () => {
withFixture({}, ({ manifestPath }) => {
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
manifest.tests[0].expectedBefore = 'fail';
writeFileSync(manifestPath, JSON.stringify(manifest));
assert.equal(run(manifestPath, 'post').status, 1);
});
withFixture({}, ({ fixtureRoot, manifestPath }) => {
const fixturePath = path.relative(projectRoot, fixtureRoot).replaceAll('\\', '/');
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
manifest.tests = [{ id: 'blocked-test', file: `${fixturePath}/tests/migration.test.mjs`, level: 'unit', expectedBefore: 'pass', status: 'blocked', blocker: 'requires staging credential' }];
writeFileSync(manifestPath, JSON.stringify(manifest));
assert.equal(run(manifestPath, 'post').status, 0);
});
});
test('post phase runs unblocked verification commands and rejects nonzero results', () => {
withFixture({ verification: { commands: ['node -e "process.exit(7)"'] } }, ({ manifestPath }) => {
assert.equal(run(manifestPath, 'post').status, 1);
});
});
test('invalid command-line arguments exit with usage status', () => {
const result = run(path.join(projectRoot, 'missing.json'), 'invalid');
assert.equal(result.status, 2);
});
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
test('upload configuration excludes migration docs, tests, and scripts', () => {
const config = JSON.parse(readFileSync(path.join(projectRoot, 'project.config.json'), 'utf8'));
const ignored = new Set((config.packOptions?.ignore || []).map(({ value }) => value));
for (const directory of ['docs', 'tests', 'scripts']) {
assert.ok(ignored.has(directory), `${directory} must be excluded from upload`);
}
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!