import { hash } from 'node:crypto' import { readFile, readdir } from 'node:fs/promises' import { readFileSync } from 'node:fs' import { join, resolve } from 'node:path' import { inParallel, isPathInside, matchesStored, read, writesToDisk } from '@internals/utils' import { type Config, createLockfile, fsStorage, hasOutputPasses, type Hookable, type KubbHooks, type Lockfile, type Storage } from '@kubb/core' /** A changed file with how many lines it gains and loses, counted as a multiset, which is cheap and close enough for a plan. */ export type FileChange = { status: 'A' | 'M' | 'D'; path: string; added?: number; removed?: number } type Lines = Iterable function splitLines(text: string): Array { return text ? text.split('\n') : [] } // An index loop over UTF-16 code units: this runs over every line of the old output on each clean run, and `for…of` // with `codePointAt` takes about twice as long. Both sides of a diff are hashed in the same run, so code units suffice. function hashLine(line: string): number { let hash = 0x811c9dc5 for (let i = 0; i < line.length; i++) hash = Math.imul(hash ^ line.charCodeAt(i), 0x01000193) return hash } function hashLines(text: string): Int32Array { return Int32Array.from(splitLines(text), hashLine) } function countLineChanges({ before, after }: { before: Lines; after: Lines }): { added: number; removed: number } { const remaining = new Map() for (const line of before) remaining.set(line, (remaining.get(line) ?? 0) + 1) const added = [...after].filter((line) => { const count = remaining.get(line) ?? 0 if (count === 0) return true remaining.set(line, count - 1) return false }).length const removed = [...remaining.values()].reduce((sum, count) => sum + count, 0) return { added, removed } } /** * Reads the output before generation, so cleaning cannot erase the diff baseline. It holds every file's text, so only * a dry run and a run with output passes use it. */ export async function readOutputFiles(outputPath: string): Promise> { const entries = await readdir(outputPath, { recursive: true, withFileTypes: true }).catch(() => []) const files = new Map() await inParallel({ items: entries.filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name)), limit: 50, run: async (filePath) => { const source = await read(filePath).catch(() => null) if (source !== null) files.set(filePath, source) }, }) return files } /** Hashes of a file `output.clean` deleted, enough to tell whether its regenerated copy changed and by how many lines. */ export type FileFingerprint = { length: number digest: string lines: Int32Array deletedLines: number } export function fingerprintFile(text: string): FileFingerprint { const body = text.trimEnd() const trimmed = body.trimStart() // A deleted file also counts the blank lines above its first line, which trimming drops. const leading = body.slice(0, body.length - trimmed.length).split('\n').length - 1 const lines = hashLines(trimmed) return { length: trimmed.length, digest: hash('sha1', trimmed), lines, deletedLines: body ? lines.length + leading : 0 } } /** Fingerprints every file under the output folder right before `output.clean` empties it, one file at a time. */ export async function readOutputFingerprints(outputPath: string): Promise> { const entries = await readdir(outputPath, { recursive: true, withFileTypes: true }).catch(() => []) const fingerprints = new Map() for (const entry of entries) { if (!entry.isFile()) continue const filePath = join(entry.parentPath, entry.name) try { // Synchronous on purpose: one read at a time is several times faster here than a pool of `fs.promises` reads. fingerprints.set(filePath, fingerprintFile(readFileSync(filePath, 'utf8'))) } catch { /* unreadable, so it cannot be compared */ } } return fingerprints } /** An unchanged file: `'lockfile'` when only `kubb-lock.json` matched it, `undefined` when the text is the same. */ export type Unchanged = 'lockfile' | undefined /** * How one generated file differs from its copy before generation. `previous` is the stored text, the * {@link FileFingerprint} of a file `output.clean` deleted, or `null` for a new file. */ export function diffFile({ path, next, previous, lockfile, }: { path: string next: string previous: string | FileFingerprint | null lockfile?: Pick }): FileChange | Unchanged { if (previous === null) return { status: 'A', path, added: splitLines(next.trimEnd()).length, removed: 0 } if (typeof previous !== 'string') { const trimmed = next.trim() if (trimmed.length === previous.length && hash('sha1', trimmed) === previous.digest) return undefined return { status: 'M', path, ...countLineChanges({ before: previous.lines, after: hashLines(trimmed) }) } } if (matchesStored({ stored: previous, source: next })) return undefined if (lockfile?.matches({ key: path, source: next, disk: previous })) return 'lockfile' return { status: 'M', path, ...countLineChanges({ before: splitLines(previous.trim()), after: splitLines(next.trim()) }) } } /** The totals the summary prints, and how many unchanged files only `kubb-lock.json` recognized. */ export type ChangeTally = { added: number modified: number deleted: number linesAdded: number linesRemoved: number unchanged: number fromLockfile: number } export const changeStatusNames = { A: 'added', M: 'modified', D: 'deleted' } as const function tallyChange({ tally, change }: { tally: ChangeTally; change: FileChange | Unchanged }): void { if (change === undefined || change === 'lockfile') { tally.unchanged++ if (change === 'lockfile') tally.fromLockfile++ return } tally[changeStatusNames[change.status]]++ tally.linesAdded += change.added ?? 0 tally.linesRemoved += change.removed ?? 0 } export function createChangeTally(): ChangeTally { return { added: 0, modified: 0, deleted: 0, linesAdded: 0, linesRemoved: 0, unchanged: 0, fromLockfile: 0 } } /** * Compares each generated file in `paths` with its copy from before generation, 50 at a time. Shared by `--dry-run` * and `--check`. */ export async function forEachChangedFile({ paths, readAfter, readBefore, lockfile, onChange, }: { paths: ReadonlySet readAfter: (path: string) => Promise readBefore: (path: string) => Promise lockfile?: Pick onChange: (changed: { change: FileChange; before: string | null; after: string; index: number }) => void }): Promise<{ unchanged: number; fromLockfile: number }> { const counts = { unchanged: 0, fromLockfile: 0 } await inParallel({ items: [...paths], limit: 50, run: async (filePath, index) => { const [after, before] = await Promise.all([readAfter(filePath), readBefore(filePath)]) if (after === null) return const change = diffFile({ path: filePath, next: after, previous: before, lockfile }) if (change === undefined || change === 'lockfile') { counts.unchanged++ if (change === 'lockfile') counts.fromLockfile++ return } onChange({ change, before, after, index }) }, }) return counts } /** Compares generated output with the files captured before generation, and with `clean` the files it would delete. */ export async function diffOutput({ storage, paths, clean, lockfile, previousFiles, }: { storage: Storage paths: ReadonlySet clean: boolean lockfile?: Pick previousFiles: ReadonlyMap }): Promise<{ files: Array; unchanged: number; fromLockfile: number }> { const changes: Array = [] const { unchanged, fromLockfile } = await forEachChangedFile({ paths, readAfter: (filePath) => storage.readItem(filePath), readBefore: async (filePath) => previousFiles.get(filePath) ?? null, lockfile, onChange: ({ change, index }) => { changes[index] = change }, }) const files = changes.filter(Boolean) if (clean) { for (const [filePath, source] of previousFiles) { if (!paths.has(filePath)) files.push({ status: 'D', path: filePath, added: 0, removed: splitLines(source.trimEnd()).length }) } } return { files, unchanged, fromLockfile } } type LiveChanges = { tally: ChangeTally // The files `output.clean` is about to delete, the only trace of them once the folder is emptied. fingerprints: Map processed: Set } type TrackedRun = { outputPath: string filesUnchanged: number paths: Set // Read-back runs only: the whole output as it was before generation. previous?: Map reading?: Promise> // A run without output passes counts each file as it is written, against the stored text the write already read. live?: LiveChanges } async function countLiveRun({ live, paths, storage }: { live: LiveChanges; paths: Set; storage: Storage }): Promise { const { tally, fingerprints, processed } = live for (const [filePath, fingerprint] of fingerprints) { if (!paths.has(filePath)) tallyChange({ tally, change: { status: 'D', path: filePath, removed: fingerprint.deletedLines } }) } // A blank file left whatever the storage held in place, so a stored copy counts as unchanged. for (const filePath of paths.difference(processed)) { if ((await storage.readItem(filePath)) !== null) tally.unchanged++ } return tally } /** What a generation wrote, as {@link FileChangeTracker} hands it over when the generation ends. */ export type TrackedGeneration = { filesUnchanged: number paths: ReadonlySet /** The run's totals, or undefined when it was not counted. Call it in `kubb:generation:end`, once. */ count: (context: { config: Config; storage: Storage }) => Promise } export type FileChangeTrackerOptions = { hooks: Hookable /** Whether to count a generation's changes. A run that counts nothing still reports its paths. */ enabled: boolean /** A dry run writes to memory, so it compares through the lockfile on disk. */ dryRun?: boolean /** Set to `false` to count the changes of a dry run without `kubb-lock.json`. */ lockfile?: boolean } /** * Counts what each generation changes in its output, from the `KubbHooks` it emits. A run counts each file as it is * written. A dry run, or a run with output passes that rewrite files after the write, reads the output back at the end * instead. Call `take()` in `kubb:generation:end`: configs generate one at a time, so the last generation started is * the one that ends. */ export class FileChangeTracker { readonly #enabled: boolean readonly #dryRun: boolean readonly #lockfile: boolean #run: TrackedRun | undefined constructor({ hooks, enabled, dryRun = false, lockfile = true }: FileChangeTrackerOptions) { this.#enabled = enabled this.#dryRun = dryRun this.#lockfile = lockfile hooks.hook('kubb:generation:start', ({ config }) => this.#startGeneration(config)) hooks.hook('kubb:plugins:end', ({ config }) => this.#readBaseline(config)) hooks.hook('kubb:files:processing:start', ({ files }) => this.#readOutsideOutput(files)) hooks.hook('kubb:file:processed', ({ file, source, stored = null }) => this.#countWrite({ path: file.path, source, stored })) hooks.hook('kubb:files:processing:end', ({ files, unchanged }) => { if (!this.#run) return this.#run.filesUnchanged = unchanged.length this.#run.paths = new Set(files.map((file) => file.path)) }) } take(): TrackedGeneration | undefined { const current = this.#run this.#run = undefined if (!current) return undefined return { filesUnchanged: current.filesUnchanged, paths: current.paths, count: (context) => this.#count({ run: current, ...context }) } } #startGeneration(config: Config): void { const outputPath = resolve(config.root, config.output.path) const tracked = this.#enabled && (this.#dryRun || writesToDisk(config.storage)) // Output passes rewrite stored files and a dry run compares through the lockfile, so both read the output back. const live = tracked && !this.#dryRun && !hasOutputPasses(config) ? { tally: createChangeTally(), fingerprints: new Map(), processed: new Set() } : undefined this.#run = { outputPath, filesUnchanged: 0, paths: new Set(), live, // Read while the plugins generate. `kubb:plugins:end` waits for it, so cleaning cannot erase the baseline first. reading: tracked && !live ? readOutputFiles(outputPath) : undefined, } } async #readBaseline(config: Config): Promise { const run = this.#run if (!run) return if (run.reading) run.previous = await run.reading // The last moment the old files exist: the storage empties the folder right after this hook. if (run.live && config.output.clean) run.live.fingerprints = await readOutputFingerprints(run.outputPath) } async #readOutsideOutput(files: ReadonlyArray<{ path: string }>): Promise { const run = this.#run if (!run?.previous) return for (const file of files) { if (run.previous.has(file.path) || isPathInside(run.outputPath, file.path)) continue const source = await readFile(file.path, 'utf8').catch(() => null) if (source !== null) run.previous.set(file.path, source) } } #countWrite({ path, source, stored }: { path: string; source: string; stored: string | null }): void { const live = this.#run?.live // The storage writes the trimmed source and skips a blank one, which leaves the stored file as it was. const next = source.trim() if (!live || !next) return live.processed.add(path) tallyChange({ tally: live.tally, change: diffFile({ path, next, previous: stored ?? live.fingerprints.get(path) ?? null }) }) } async #count({ run, config, storage }: { run: TrackedRun; config: Config; storage: Storage }): Promise { const { live, paths, previous } = run if (live) return countLiveRun({ live, paths, storage }) if (!previous) return undefined // A dry run writes to memory, so the lockfile that describes the files on disk is read from disk. const lockfileOnDisk = this.#dryRun && this.#lockfile ? await createLockfile({ storage: fsStorage(), root: config.root }) : undefined const diff = await diffOutput({ storage, paths, clean: Boolean(config.output.clean), lockfile: lockfileOnDisk, previousFiles: previous }) const tally = createChangeTally() tally.unchanged = diff.unchanged tally.fromLockfile = diff.fromLockfile for (const change of diff.files) tallyChange({ tally, change }) return tally } } export function createFileChangeTracker(options: FileChangeTrackerOptions): FileChangeTracker { return new FileChangeTracker(options) }