check-migration-readiness.mjs 6.81 KB
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();