affected-tests.mjs 11.1 KB
/**
 * @file 根据 Git 变更集和知识图谱选择需要执行的离线测试。
 */

import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { buildKnowledgeGraph } from './build-knowledge-graph.mjs'

export const FULL_TEST_ROOTS = [
  'tabWorkOrder/pages/createOrder/tests',
  'tests',
  'packageDynamicForm/tests',
  'tabIndex/tests',
  'packageEquity/tests',
  'tabWorkOrder/pages/refundApply/tests/refundApplyMarketing.test.mjs',
  'packageDynamicForm/pages/upgradeStaffDaily/tests/dailyReportInconsistency.helpers.test.mjs',
]

const DOCS_TESTS = [
  'tests/knowledge-graph/artifactsAndImpact.test.mjs',
  'tests/knowledge-graph/buildKnowledgeGraph.test.mjs',
  'tests/project-governance/agentDocsLayout.test.mjs',
]
const FULL_EXACT_FILES = new Set([
  'app.js',
  'app.json',
  'package.json',
  'package-lock.json',
  'npm-shrinkwrap.json',
  'yarn.lock',
  'pnpm-lock.yaml',
])
const SHARED_ROOTS = ['components/', 'api/', 'store/', 'utils/']
const DEV_ONLY_ROOTS = ['docs/', 'scripts/', 'tests/', '.agents/', '.github/']
const KNOWLEDGE_TOOLING_ROOTS = [
  'scripts/knowledge-graph/',
  'tests/knowledge-graph/',
]

function compareText(left, right) {
  return left < right ? -1 : left > right ? 1 : 0
}

function normalizeFiles(files) {
  return [...new Set((files || []).map((file) => file.replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean))].sort(compareText)
}

function fullPlan(changedFiles, reasons, tests) {
  return {
    mode: 'full',
    reasons: [...new Set(reasons)].sort(compareText),
    changedFiles,
    domains: [],
    tests,
    commands: ['npm test'],
    unresolved: [],
  }
}

function testFiles(graph) {
  return graph.nodes
    .filter((node) => node.type === 'test' && node.path)
    .map((node) => node.path)
    .sort(compareText)
}

function nodeIdsForChangedFiles(graph, changedFiles) {
  const paths = new Set(changedFiles)
  return new Set(
    graph.nodes
      .filter((node) => node.path && paths.has(node.path))
      .map((node) => node.id),
  )
}

function consumerClosure(graph, seeds, depth = 3) {
  const relevant = new Set(seeds)
  let frontier = new Set(seeds)
  for (let level = 0; level < depth; level += 1) {
    const next = new Set()
    for (const edge of graph.edges) {
      if (!frontier.has(edge.to)) continue
      if (!['imports', 'calls', 'callsApi', 'usesComponent', 'contains'].includes(edge.type)) {
        continue
      }
      if (relevant.has(edge.from)) continue
      relevant.add(edge.from)
      next.add(edge.from)
    }
    frontier = next
    if (!frontier.size) break
  }
  return relevant
}

function relatedTests(graph, relevantIds) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  const relevantPaths = new Set(
    [...relevantIds].map((id) => nodeById.get(id)?.path).filter(Boolean),
  )
  const tests = new Set()
  for (const edge of graph.edges) {
    const from = nodeById.get(edge.from)
    const to = nodeById.get(edge.to)
    if (to?.type !== 'test') continue
    if (
      relevantIds.has(edge.from) ||
      relevantPaths.has(from?.path) ||
      (edge.type === 'imports' && relevantIds.has(edge.to))
    ) {
      tests.add(to.path)
    }
  }
  for (const id of relevantIds) {
    const node = nodeById.get(id)
    if (node?.type === 'test') tests.add(node.path)
  }
  return [...tests].sort(compareText)
}

function domainsForChanges(graph, changedIds) {
  const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
  return [...new Set([...changedIds].map((id) => nodeById.get(id)?.domain).filter(Boolean))].sort(compareText)
}

/**
 * 选择某个变更集对应的测试计划。
 *
 * @param {{graph: object, changedFiles: string[], forceFull?: boolean}} options 图谱、变更路径和强制全量开关。
 * @returns {{mode: string, reasons: string[], changedFiles: string[], domains: string[], tests: string[], commands: string[], unresolved: object[]}} 测试计划。
 */
export function selectAffectedTests({ graph, changedFiles, forceFull = false }) {
  const files = normalizeFiles(changedFiles)
  const allTests = testFiles(graph)
  if (forceFull) return fullPlan(files, ['forced-full'], allTests)
  if (!files.length) {
    return {
      mode: 'none',
      reasons: ['no-local-changes'],
      changedFiles: [],
      domains: [],
      tests: [],
      commands: [],
      unresolved: [],
    }
  }

  const documentationOnly = files.every((file) =>
    ['docs/', '.agents/'].some((root) => file.startsWith(root)),
  )
  if (documentationOnly) {
    const knowledgeConfigChange = files.some((file) =>
      file.startsWith('docs/knowledge/'),
    )
    return {
      mode: 'docs-only',
      reasons: [
        knowledgeConfigChange ? 'knowledge-config-change' : 'documentation-only',
      ],
      changedFiles: files,
      domains: [],
      tests: knowledgeConfigChange
        ? ['tests/knowledge-graph', 'tests/project-governance']
        : DOCS_TESTS,
      commands: ['npm run knowledge:check'],
      unresolved: [],
    }
  }

  const reasons = []
  if (files.some((file) => FULL_EXACT_FILES.has(file))) reasons.push('global-entry-or-dependency')
  if (files.some((file) => SHARED_ROOTS.some((root) => file.startsWith(root)))) {
    reasons.push('shared-runtime-layer')
  }
  const changedIds = nodeIdsForChangedFiles(graph, files)
  const domains = domainsForChanges(graph, changedIds)
  if (domains.length > 1) reasons.push('cross-domain-change')
  const unresolved = graph.unresolved.filter((item) => files.includes(item.path))
  if (unresolved.length) reasons.push('unresolved-relation')
  const unclassifiedRuntime = files.some((file) => {
    if (DEV_ONLY_ROOTS.some((root) => file.startsWith(root))) return false
    if (/\.(?:md|txt|pdf|docx)$/i.test(file)) return false
    return !graph.nodes.some((node) => node.path === file && node.domain)
  })
  if (unclassifiedRuntime) reasons.push('unclassified-runtime-file')
  if (
    files.some(
      (file) =>
        file.startsWith('scripts/') &&
        !file.startsWith('scripts/knowledge-graph/'),
    )
  ) {
    reasons.push('unclassified-tooling-file')
  }
  if (reasons.length) {
    const plan = fullPlan(files, reasons, allTests)
    plan.domains = domains
    plan.unresolved = unresolved
    return plan
  }

  const relevantIds = consumerClosure(graph, changedIds)
  const targetedReasons = []
  const toolingTests = []
  if (
    files.some((file) =>
      KNOWLEDGE_TOOLING_ROOTS.some((root) => file.startsWith(root)),
    )
  ) {
    targetedReasons.push('knowledge-tooling-change')
    toolingTests.push('tests/knowledge-graph')
  }
  if (files.some((file) => file.startsWith('.github/'))) {
    targetedReasons.push('automation-config-change')
    toolingTests.push('tests/project-governance')
  }
  if (domains.length) targetedReasons.push('page-local-change')
  const selected = [
    ...new Set([
      ...relatedTests(graph, relevantIds),
      ...graph.nodes
        .filter((node) => node.type === 'test' && domains.includes(node.domain))
        .map((node) => node.path),
      ...toolingTests,
    ]),
  ].sort(compareText)
  if (!selected.length) {
    const plan = fullPlan(files, ['no-test-candidates'], allTests)
    plan.domains = domains
    return plan
  }
  return {
    mode: 'targeted',
    reasons: [...new Set(targetedReasons.length ? targetedReasons : ['page-local-change'])].sort(compareText),
    changedFiles: files,
    domains,
    tests: selected,
    commands: [],
    unresolved: [],
  }
}

function gitLines(rootDir, args) {
  const result = spawnSync('git', args, { cwd: rootDir, encoding: 'utf8' })
  if (result.status !== 0) throw new Error(result.stderr.trim() || `git ${args.join(' ')} failed`)
  return result.stdout.split(/\r?\n/).filter(Boolean)
}

/**
 * 读取本地未提交变更,或 CI 指定的 base/head 变更范围。
 *
 * @param {{rootDir: string, base?: string, head?: string}} options Git 根目录和可选引用。
 * @returns {string[]} 固定排序的变更路径。
 */
export function readChangedFiles({ rootDir, base, head }) {
  if ((base && !head) || (!base && head)) throw new Error('--base and --head must be used together')
  if (base && head) {
    return normalizeFiles(gitLines(rootDir, ['diff', '--no-renames', '--name-only', '--diff-filter=ACMRD', base, head]))
  }
  return normalizeFiles([
    ...gitLines(rootDir, ['diff', '--no-renames', '--name-only', '--diff-filter=ACMRD']),
    ...gitLines(rootDir, ['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=ACMRD']),
    ...gitLines(rootDir, ['ls-files', '--others', '--exclude-standard']),
  ])
}

/**
 * 从当前工作树构建 affected 专用图谱,避免受已提交生成物漂移影响。
 *
 * @param {string} rootDir 项目根目录。
 * @returns {Promise<object>} 当前源码对应的内存图谱。
 */
export async function buildCurrentGraph(rootDir) {
  return buildKnowledgeGraph({ rootDir })
}

function parseArguments(argv) {
  const result = {
    base: null,
    head: null,
    list: false,
    format: 'text',
    verbose: false,
    full: false,
  }
  for (let index = 0; index < argv.length; index += 1) {
    const argument = argv[index]
    if (argument === '--base') result.base = argv[++index]
    else if (argument === '--head') result.head = argv[++index]
    else if (argument === '--list') result.list = true
    else if (argument === '--format') result.format = argv[++index]
    else if (argument === '--verbose') result.verbose = true
    else if (argument === '--full') result.full = true
    else throw new Error(`unknown argument: ${argument}`)
  }
  return result
}

function printPlan(plan, format) {
  if (format === 'json') {
    console.log(JSON.stringify(plan, null, 2))
    return
  }
  console.log(`mode: ${plan.mode}`)
  console.log(`reasons: ${plan.reasons.join(', ') || 'none'}`)
  console.log(`domains: ${plan.domains.join(', ') || 'none'}`)
  console.log(`tests: ${plan.tests.length}`)
  for (const testFile of plan.tests) console.log(`- ${testFile}`)
}

function runNodeTests(rootDir, targets, verbose) {
  if (!targets.length) return 0
  const reporter = verbose ? 'spec' : 'dot'
  const result = spawnSync(
    process.execPath,
    ['--experimental-detect-module', '--test', `--test-reporter=${reporter}`, ...targets],
    { cwd: rootDir, stdio: 'inherit' },
  )
  return result.status ?? 1
}

async function main() {
  const rootDir = process.cwd()
  const options = parseArguments(process.argv.slice(2))
  const graph = await buildCurrentGraph(rootDir)
  const changedFiles = readChangedFiles({
    rootDir,
    base: options.base,
    head: options.head,
  })
  const plan = selectAffectedTests({ graph, changedFiles, forceFull: options.full })
  printPlan(plan, options.format)
  if (options.list || plan.mode === 'none') return
  if (plan.mode === 'docs-only') {
    const check = spawnSync('npm', ['run', 'knowledge:check'], { cwd: rootDir, stdio: 'inherit', shell: process.platform === 'win32' })
    if (check.status !== 0) {
      process.exitCode = check.status ?? 1
      return
    }
  }
  process.exitCode = runNodeTests(
    rootDir,
    plan.mode === 'full' ? FULL_TEST_ROOTS : plan.tests,
    options.verbose,
  )
}

const isMain =
  process.argv[1] &&
  path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
if (isMain) await main()