All files / packages/design-system/scripts/validation compare-output-patch-pairs.js

42.85% Statements 54/126
43.33% Branches 26/60
71.42% Functions 10/14
37.5% Lines 42/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 3342x                                 2x     72x 72x 66x       42x 42x 42x 109x   1x                                                   7x 4x       4x     10x   4x                                             7x 4x     4x       13x     4x   7x 7x       1x   6x   1x       10x 10x 49x 49x 47x 47x 47x     10x 10x 22x 27x 21x 21x           21x   17x     10x 10x                                                                                                                                                                                                                                                                                                                                                                                              
import path from 'node:path';
import { execSync } from 'node:child_process';
import fs from 'fs-extra';
import chalk from 'chalk';
 
import {
  getShortSha,
  resolveConfigPath,
  loadConfig,
  resolveCompareSettings,
  collectCompareHooks,
  createReportDir,
  buildReport,
  writeReportFiles,
  writeHtmlDiffFiles,
} from './compare-output-core.js';
 
const VERSIONED_FILE_RE = /^(.+)-(\d+\.\d+\.\d+)\.(\w+)$/;
 
export function parseVersionedFile(filename) {
  const match = VERSIONED_FILE_RE.exec(filename);
  if (!match) return null;
  return { family: match[1], version: match[2], ext: match[3] };
}
 
export function compareSemver(a, b) {
  const aParts = a.split('.').map(Number);
  const bParts = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if (aParts[i] !== bParts[i]) return aParts[i] - bParts[i];
  }
  return 0;
}
 
/**
 * Get filenames introduced in the current release.
 *
 * Runs `git diff --name-only --diff-filter=AR <addedSince>...HEAD -- <sourceDir>`
 * inside the source directory's git repo and returns the basename set. The
 * `AR` filter captures both fresh adds (e.g. a new minor like
 * `slds-plus-2.4.2.css`) and renames where the prior-version file was bumped
 * to a new filename (e.g. the SCS pipeline's `git mv slds-2.30.4.css
 * slds-2.30.6.css` for files whose contents are mostly unchanged).
 *
 * Used to scope patch-pair detection to files this release introduced —
 * without this filter, every family in the source dir gets paired (including
 * untouched historical pairs like a deprecated `theme-layer` line).
 *
 * Returns null when `addedSince` is not configured (caller treats as "no
 * filter, pair every family").
 *
 * @param {string} sourceDir
 * @param {string|null|undefined} addedSince
 * @param {(cmd: string, opts?: object) => string|Buffer} [execSyncFn]
 * @returns {Set<string>|null}
 */
export function getAddedFilenames(sourceDir, addedSince, execSyncFn = execSync) {
  if (!addedSince) return null;
  const stdout = execSyncFn(
    `git diff --name-only --diff-filter=AR ${addedSince}...HEAD -- ${sourceDir}`,
    { cwd: sourceDir, encoding: 'utf8' },
  );
  return new Set(
    String(stdout)
      .split('\n')
      .map((line) => line.trim())
      .filter(Boolean)
      .map((p) => path.basename(p)),
  );
}
 
/**
 * Resolve a package version (e.g. `0.0.140`) to the commit that shipped it.
 *
 * This is the correct anchor for a patch comparison: we want to diff against
 * the committed state of the slds-scs branch *at the previous release*, not a
 * positional ref like `HEAD~1`. `HEAD~1` is fragile — interleaved commits
 * (`Update CODEOWNERS`, `revert`, merge commits) between the prior release and
 * the assemble commit make it point at the wrong tree. The package version is
 * the release's real identity, so we walk `package.json`'s history newest-first
 * and return the most recent commit whose `package.json` version equals the arg.
 *
 * Returns null when the version can't be found in history.
 *
 * @param {string} sourceDir - a path inside the target git repo (e.g. the clone's `slds/`)
 * @param {string|null|undefined} version - the previous release's package version
 * @param {(cmd: string, opts?: object) => string|Buffer} [execSyncFn]
 * @returns {string|null} the resolved commit SHA, or null
 */
export function resolvePackageVersionRef(sourceDir, version, execSyncFn = execSync) {
  if (!version) return null;
  const repoRoot = String(
    execSyncFn('git rev-parse --show-toplevel', { cwd: sourceDir, encoding: 'utf8' }),
  ).trim();
  const revs = String(
    execSyncFn('git rev-list HEAD -- package.json', { cwd: repoRoot, encoding: 'utf8' }),
  )
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean);
 
  for (const sha of revs) {
    let parsed;
    try {
      parsed = JSON.parse(
        String(execSyncFn(`git show ${sha}:package.json`, { cwd: repoRoot, encoding: 'utf8' })),
      );
    } catch {
      continue;
    }
    if (parsed && parsed.version === version) return sha;
  }
  return null;
}
 
export function selectPatchPairs(filenames, { addedFilenames = null } = {}) {
  const families = new Map();
  for (const filename of filenames) {
    const parsed = parseVersionedFile(filename);
    if (!parsed) continue;
    const key = `${parsed.family}.${parsed.ext}`;
    if (!families.has(key)) families.set(key, []);
    families.get(key).push({ filename, ...parsed });
  }
 
  const pairs = [];
  for (const entries of families.values()) {
    if (entries.length < 2) continue;
    entries.sort((a, b) => compareSemver(a.version, b.version));
    const newest = entries[entries.length - 1];
    const previous = entries[entries.length - 2];
 
    // When `addedFilenames` is provided, only emit pairs where the newer file
    // was added by the current release. Skips families this release didn't
    // touch (e.g. deprecated lines whose newest two versions both pre-date
    // the release branch).
    if (addedFilenames && !addedFilenames.has(newest.filename)) continue;
 
    pairs.push({ family: newest.family, ext: newest.ext, previous, newest });
  }
 
  pairs.sort((a, b) => a.family.localeCompare(b.family));
  return pairs;
}
 
export function comparePatchPairs({
  pairs,
  sourceDir,
  compareFiles,
  beforeCompareHooks,
  afterCompareHooks,
  log = console.log,
}) {
  const results = [];
  const counts = { identical: 0, different: 0, added: 0, removed: 0 };
 
  for (const pair of pairs) {
    const previousPath = path.join(sourceDir, pair.previous.filename);
    const newestPath = path.join(sourceDir, pair.newest.filename);
    const relativePath = `${pair.previous.filename} → ${pair.newest.filename}`;
 
    let result = compareFiles(previousPath, newestPath, beforeCompareHooks);
    if (!result) continue;
 
    result.relativePath = relativePath;
    result.baselinePath = previousPath;
    result.currentPath = newestPath;
 
    for (const hook of afterCompareHooks) {
      result = hook(result, relativePath);
    }
 
    results.push(result);
 
    switch (result.status) {
      case 'identical':
        counts.identical++;
        log(chalk.green(`   ✓ ${relativePath}`));
        break;
      case 'different':
        counts.different++;
        log(chalk.yellow(`   ⚠ ${relativePath} (+${result.linesAdded} -${result.linesRemoved})`));
        break;
      default:
        break;
    }
  }
 
  return { results, counts };
}
 
export async function compareOutputPatchPairs(
  cliArgs,
  {
    cwd = process.cwd(),
    fsImpl = fs,
    log = console.log,
    now = () => new Date(),
    execSyncFn,
    deps = {},
  } = {},
) {
  const requiredDeps = [
    'compareFiles',
    'findFiles',
    'generateHtmlDiff',
    'generateIndexHtml',
    'generateTextReport',
  ];
  for (const key of requiredDeps) {
    if (typeof deps[key] !== 'function') {
      throw new Error(`Missing required dependency: ${key}`);
    }
  }
 
  const configPath = resolveConfigPath(cliArgs.config, cwd);
  const config = await loadConfig(configPath);
  const { name, sourceDir, outputDir, globPattern, failOnDiff, plugins } =
    resolveCompareSettings(config, cliArgs, cwd);
 
  log(chalk.blue(`🔍 Comparing patch pairs: ${name}\n`));
  log(chalk.gray(`   Source: ${sourceDir}`));
  log(chalk.gray(`   Output: ${outputDir}`));
  log(chalk.gray(`   Pattern: ${globPattern}\n`));
 
  if (!fsImpl.existsSync(sourceDir)) {
    throw new Error(`Source directory not found: ${sourceDir}`);
  }
 
  const timestamp = now();
  const shortSha = execSyncFn ? getShortSha(execSyncFn) : getShortSha();
  const reportDir = createReportDir({ outputDir, timestamp, shortSha, fsImpl });
  const { beforeCompareHooks, afterCompareHooks } = collectCompareHooks(plugins);
 
  const filenames = deps.findFiles(sourceDir, globPattern);
 
  // Resolve the anchor that identifies which files this release introduced.
  // Two ways to specify it, in precedence order:
  //   1. --added-since-package-version=<v> — the previous release's package
  //      version, resolved to the committed slds-scs branch state that shipped
  //      it. This is the robust, release-identity anchor (see
  //      resolvePackageVersionRef). Preferred for patch releases.
  //   2. --added-since=<ref> — a raw git ref (branch/tag/SHA). An escape hatch.
  // Patch-pairs mode MUST have an anchor. Without one, the tool has no notion
  // of "new this release" and would fall back to pairing the two newest files
  // in every family — fabricating diffs for untouched historical families. That
  // fallback is never correct, so we refuse to run instead.
  const addedSinceVersion =
    cliArgs.addedSincePackageVersion || config.addedSincePackageVersion || null;
  const addedSinceRaw = cliArgs.addedSince || config.addedSince || null;
 
  let addedSince = addedSinceRaw;
  if (addedSinceVersion) {
    addedSince = resolvePackageVersionRef(sourceDir, addedSinceVersion, execSyncFn);
    if (!addedSince) {
      throw new Error(
        `Could not resolve --added-since-package-version=${addedSinceVersion}: ` +
          `no commit in ${sourceDir}'s repo has that version in package.json.`,
      );
    }
    log(
      chalk.gray(
        `   Anchor: package version ${addedSinceVersion} → commit ${addedSince.slice(0, 9)}\n`,
      ),
    );
  }
 
  if (!addedSince) {
    throw new Error(
      'patch-pairs requires an anchor identifying the previous release state. ' +
        'Pass --added-since-package-version=<prev version> (preferred) or --added-since=<ref>. ' +
        'Without one, every family would be paired, fabricating diffs for untouched files.',
    );
  }
 
  const addedFilenames = getAddedFilenames(sourceDir, addedSince, execSyncFn);
  const pairs = selectPatchPairs(filenames, { addedFilenames });
  log(
    chalk.gray(
      `   Filtering to pairs whose newer file is in: git diff --diff-filter=AR ${addedSince}...HEAD\n`,
    ),
  );
  log(chalk.gray(`   Found ${pairs.length} patch pair(s)...\n`));
 
  const { results, counts } = comparePatchPairs({
    pairs,
    sourceDir,
    compareFiles: deps.compareFiles,
    beforeCompareHooks,
    afterCompareHooks,
    log,
  });
 
  const report = buildReport({
    name: `${name} (patch pairs)`,
    timestamp,
    shortSha,
    baselineDir: sourceDir,
    sourceDir,
    results,
    counts,
  });
 
  writeReportFiles({
    reportDir,
    report,
    fsImpl,
    generateTextReport: deps.generateTextReport,
    generateIndexHtml: deps.generateIndexHtml,
  });
 
  const filesWithDiffs = results.filter((result) => result.status !== 'identical');
  writeHtmlDiffFiles({
    filesWithDiffs,
    reportDir,
    name,
    generateHtmlDiff: deps.generateHtmlDiff,
    log,
  });
 
  log(chalk.blue('\n' + '='.repeat(50)));
  log(chalk.blue('Patch-pairs Summary:'));
  log(chalk.green(`   ✓ Identical: ${counts.identical}`));
  if (counts.different > 0) {
    log(chalk.yellow(`   ⚠ Different: ${counts.different}`));
  }
  log(chalk.blue('='.repeat(50)));
 
  log(chalk.gray(`\nReports saved to: ${reportDir}`));
 
  const shouldFailExit = (counts.different > 0) && failOnDiff;
  return { report, reportDir, counts, shouldFailExit };
}