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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | 2x 120x 120x 112x 55x 55x 55x 133x 1x 7x 4x 4x 10x 4x 9x 6x 6x 20x 20x 20x 6x 7x 4x 4x 13x 4x 7x 7x 1x 6x 1x 2x 18x 18x 77x 77x 75x 75x 75x 18x 18x 37x 40x 34x 34x 34x 29x 18x 18x 6x 8x 1x 1x 3x 3x 1x | 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)),
);
}
/**
* Identify the files a release introduced by their **artifact version**, with no
* git history.
*
* `getAddedFilenames` scopes pairs via `git diff` against a committed ref — which
* requires the new files to already be committed in a real repo. That fails for
* the **first beta of a new minor**: the newly-assembled `X.Y.0` files live in
* the gitignored working dir (`packages/slds-scs/slds`) and aren't committed
* anywhere to diff against, so the git anchor finds nothing and 0 pairs emit.
*
* This anchor instead treats "introduced this release" as "every artifact stamped
* with `version`" — a purely lexical check over the on-disk filenames. It works
* against an uncommitted assembled dir and pairs each such file with the previous
* version in its family (via `selectPatchPairs`), which is exactly the cross-minor
* diff wanted for a new-minor beta (e.g. `slds-2.264.0.css → slds-2.266.0.css`).
*
* Returns null when `version` is falsy (caller falls back to a git anchor).
*
* @param {string[]} filenames - candidate filenames (basenames) in the source dir
* @param {string|null|undefined} version - the release's artifact version (e.g. `2.266.0`)
* @returns {Set<string>|null}
*/
export function getAddedFilenamesForVersion(filenames, version) {
if (!version) return null;
const set = new Set();
for (const filename of filenames) {
const base = path.basename(filename);
const parsed = parseVersionedFile(base);
if (parsed && parsed.version === version) set.add(base);
}
return set;
}
/**
* 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 const RETENTION_EXEMPT_FAMILIES = new Set([
'slds-plus-theme-layer',
'slds-plus-pearl-subtheme',
'slds-plus-glass-subtheme',
]);
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 selectExemptSubthemePairs(filenames, { addedFilenames = null } = {}) {
return selectPatchPairs(filenames, { addedFilenames: null }).filter((pair) =>
RETENTION_EXEMPT_FAMILIES.has(pair.family),
);
}
export function mergePatchPairs(regularPairs, exemptPairs) {
const byFamily = new Map();
for (const pair of [...regularPairs, ...exemptPairs]) {
const key = `${pair.family}.${pair.ext}`;
if (!byFamily.has(key)) byFamily.set(key, pair);
}
return [...byFamily.values()].sort((a, b) => a.family.localeCompare(b.family));
}
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.
// Three ways to specify it, in precedence order:
// 1. --added-in-version=<X.Y.Z> — the release's artifact version. Scopes
// pairs to files stamped with that version, computed purely from on-disk
// filenames (no git). REQUIRED for the first beta of a new minor, whose
// new X.Y.0 files aren't committed anywhere to git-diff against — and it
// lets the report run directly against the assembled (uncommitted) dir.
// 2. --added-since-package-version=<v> — the previous release's package
// version, resolved to the committed slds-scs branch state that shipped
// it. Robust release-identity anchor for a patch on a committed branch.
// 3. --added-since=<ref> — a raw git ref (branch/tag/SHA). An escape hatch.
// Patch-pairs mode MUST have one of these. Without any, 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 addedInVersion = cliArgs.addedInVersion || config.addedInVersion || null;
const addedSinceVersion =
cliArgs.addedSincePackageVersion || config.addedSincePackageVersion || null;
const addedSinceRaw = cliArgs.addedSince || config.addedSince || null;
let addedFilenames;
if (addedInVersion) {
addedFilenames = getAddedFilenamesForVersion(filenames, addedInVersion);
if (!addedFilenames || addedFilenames.size === 0) {
throw new Error(
`Could not resolve --added-in-version=${addedInVersion}: ` +
`no files in ${sourceDir} carry that artifact version.`,
);
}
log(
chalk.gray(
` Anchor: artifact version ${addedInVersion} (${addedFilenames.size} introduced file(s))\n`,
),
);
} else {
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 which files this release introduced. ' +
'Pass --added-in-version=<X.Y.Z> (new-minor beta; runs against the assembled dir), ' +
'--added-since-package-version=<prev version>, or --added-since=<ref>. ' +
'Without one, every family would be paired, fabricating diffs for untouched files.',
);
}
addedFilenames = getAddedFilenames(sourceDir, addedSince, execSyncFn);
log(
chalk.gray(
` Filtering to pairs whose newer file is in: git diff --diff-filter=AR ${addedSince}...HEAD\n`,
),
);
}
const regularPairs = selectPatchPairs(filenames, { addedFilenames });
const exemptPairs = selectExemptSubthemePairs(filenames, { addedFilenames });
const pairs = mergePatchPairs(regularPairs, exemptPairs);
if (exemptPairs.length > 0) {
log(
chalk.gray(
` Exempt subthemes (always paired when ≥2 versions exist): ${exemptPairs
.map((p) => p.family)
.join(', ')}\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 };
}
|