Files

54 lines
1.8 KiB
JavaScript

import { createHash } from 'node:crypto'
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
/**
* Fixture files, and the R4 oracle inputs committed as generator
* descriptions (`<slug>.gen.json`, generator `concat/1`, written at the
* R4.1 freeze by the engine's generator helper, deleted at R4.8, for inputs
* over 2 MiB; `crates/core/tests/common/r4.rs` expands them).
*/
export const sha256 = (bytes) =>
createHash('sha256').update(bytes).digest('hex')
/** Files under `dir`, sorted, recursively when asked. */
export function filesUnder(dir, recursive = false) {
const files = []
for (const name of readdirSync(dir).sort()) {
const path = join(dir, name)
if (statSync(path).isDirectory()) {
if (recursive) files.push(...filesUnder(path, true))
} else {
files.push(path)
}
}
return files
}
export const isGenerator = (path) => path.endsWith('.gen.json')
function partBytes(part, dir) {
if ('latin1' in part) return Buffer.from(part.latin1, 'latin1')
if ('fill' in part) return Buffer.alloc(part.count, part.fill)
const source = readFileSync(resolve(dir, part.slice))
return source.subarray(part.start, part.end)
}
/** The bytes a description stands for, checked: length and digest. */
export function expandGenerator(path) {
const description = JSON.parse(readFileSync(path, 'utf8'))
if (description.generator !== 'concat/1') {
throw new Error(`${path}: unknown generator ${description.generator}`)
}
const parts = description.parts.map((p) => partBytes(p, dirname(path)))
const bytes = Buffer.concat(parts)
if (bytes.length !== description.length) {
throw new Error(`${path}: expands to ${bytes.length} bytes`)
}
if (sha256(bytes) !== description.sha256) {
throw new Error(`${path}: digest differs from the description`)
}
return bytes
}