feat: bhl release — артефакты версии спецификации (BHL-027)
- детерминированный tarball (ustar, сортировка путей, mtime/uid/gid=0) - manifest: SHA-256 фактических байтов каждого файла (D-012) + сумма tarball - тесты: повторная сборка идентична; tar-извлечение сверяется с manifest - реальная публикация Git Release не выполнена (D-034); пакет 44/44
This commit is contained in:
@@ -38,6 +38,7 @@ npm run bhl -- version
|
||||
| `manifest validate` | валидация манифеста проекта | работает (BHL-014, BHL-022) |
|
||||
| `fetch` / `verify` | загрузка версии спецификации, кеш и lock | работает (BHL-021) |
|
||||
| `audit` | детерминированный аудит проекта по Effective Specification | работает (BHL-026); семантический аудит — BHL-029+ |
|
||||
| `release` | артефакты версии спецификации: tarball + manifest + сумма tarball | работает (BHL-027); публикация — BHL-027/D-034 |
|
||||
|
||||
## Зависимости и границы
|
||||
|
||||
|
||||
+106
-29
@@ -5,13 +5,14 @@ import { runAudit, writeAuditReport } from './audit.ts';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { fetchSpec, verifyCache } from './fetch.ts';
|
||||
import { renderReport, renderSpec } from './render.ts';
|
||||
import { buildRelease } from './release.ts';
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import { specList, specShow, validateManifest } from './spec.ts';
|
||||
import { validateReport } from './report.ts';
|
||||
import { validateSpec } from './validate.ts';
|
||||
|
||||
const USAGE_MESSAGE =
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|fetch|verify|audit> [args]; ' +
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|fetch|verify|audit|release> [args]; ' +
|
||||
'spec list [--spec-root <path>] [--domain <id>] [--capability <id>]; ' +
|
||||
'spec show <req-id> [--spec-root <path>]; ' +
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
@@ -23,6 +24,7 @@ const USAGE_MESSAGE =
|
||||
'verify --version <semver> --cache <dir>; ' +
|
||||
'audit <project-dir> --out <report.json> [--spec-root <path>] [--profile <id>] ' +
|
||||
'[--preset <id>] [--generated-at <iso>]; ' +
|
||||
'release <spec-root> --version <semver> --out <dir>; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
|
||||
@@ -531,6 +533,89 @@ function parseAuditArgs(args: readonly string[]): AuditFlags | { error: string }
|
||||
return target;
|
||||
}
|
||||
|
||||
const RELEASE_FLAGS: Readonly<Record<string, 'version' | 'out'>> = {
|
||||
'--version': 'version',
|
||||
'--out': 'out',
|
||||
};
|
||||
|
||||
interface ReleaseFlags {
|
||||
version?: string;
|
||||
out?: string;
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
function takeReleaseFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: ReleaseFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = RELEASE_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
target[flag] = value;
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseReleaseArgs(args: readonly string[]): ReleaseFlags | { error: string } {
|
||||
const target: ReleaseFlags = { positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (RELEASE_FLAGS[arg] !== undefined) {
|
||||
const taken = takeReleaseFlag(args, cursor, target, arg);
|
||||
if ('error' in taken) {
|
||||
return taken;
|
||||
}
|
||||
cursor = taken.next;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `unknown flag ${arg}` };
|
||||
}
|
||||
target.positional.push(arg);
|
||||
cursor += 1;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function runRelease(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseReleaseArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const specRoot = parsed.positional[0];
|
||||
const version = parsed.version;
|
||||
const out = parsed.out;
|
||||
if (
|
||||
specRoot === undefined ||
|
||||
parsed.positional.length !== 1 ||
|
||||
version === undefined ||
|
||||
out === undefined
|
||||
) {
|
||||
emit(
|
||||
failEnvelope(command, 'USAGE', 'release requires <spec-root> --version <semver> --out <dir>'),
|
||||
);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = buildRelease(specRoot, version, out);
|
||||
const data = {
|
||||
spec_root: specRoot,
|
||||
version,
|
||||
out,
|
||||
files: result.files,
|
||||
errors: result.diagnostics,
|
||||
};
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(command, data, result.diagnostics.length);
|
||||
}
|
||||
emit(okEnvelope(command, data));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runAuditCommand(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseAuditArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
@@ -683,40 +768,32 @@ function runValidate(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
|
||||
const COMMAND_HANDLERS: Readonly<Record<string, (rest: readonly string[]) => number>> = {
|
||||
version: () => {
|
||||
const info = readPackageInfo();
|
||||
emit(okEnvelope('version', { name: info.name, version: info.version }));
|
||||
return ExitCode.Ok;
|
||||
},
|
||||
profile: (rest) => runProfile('profile', rest),
|
||||
validate: (rest) => runValidate('validate', rest),
|
||||
spec: (rest) => runSpec('spec', rest),
|
||||
manifest: (rest) => runManifest('manifest', rest),
|
||||
report: (rest) => runReport('report', rest),
|
||||
fetch: (rest) => runFetch('fetch', rest),
|
||||
verify: (rest) => runVerify('verify', rest),
|
||||
audit: (rest) => runAuditCommand('audit', rest),
|
||||
release: (rest) => runRelease('release', rest),
|
||||
};
|
||||
|
||||
export function run(argv: readonly string[]): number {
|
||||
const [command, ...rest] = argv;
|
||||
if (command === undefined) {
|
||||
emit(failEnvelope('none', 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
if (command === 'version') {
|
||||
const info = readPackageInfo();
|
||||
emit(okEnvelope('version', { name: info.name, version: info.version }));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
if (command === 'profile') {
|
||||
return runProfile(command, rest);
|
||||
}
|
||||
if (command === 'validate') {
|
||||
return runValidate(command, rest);
|
||||
}
|
||||
if (command === 'spec') {
|
||||
return runSpec(command, rest);
|
||||
}
|
||||
if (command === 'manifest') {
|
||||
return runManifest(command, rest);
|
||||
}
|
||||
if (command === 'report') {
|
||||
return runReport(command, rest);
|
||||
}
|
||||
if (command === 'fetch') {
|
||||
return runFetch(command, rest);
|
||||
}
|
||||
if (command === 'verify') {
|
||||
return runVerify(command, rest);
|
||||
}
|
||||
if (command === 'audit') {
|
||||
return runAuditCommand(command, rest);
|
||||
const handler = COMMAND_HANDLERS[command];
|
||||
if (handler !== undefined) {
|
||||
return handler(rest);
|
||||
}
|
||||
emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export interface ReleaseResult {
|
||||
ok: boolean;
|
||||
files: readonly string[];
|
||||
diagnostics: readonly { file: string; code: string; message: string }[];
|
||||
}
|
||||
|
||||
interface TarEntry {
|
||||
name: string;
|
||||
bytes: Buffer;
|
||||
}
|
||||
|
||||
function sha256(data: Buffer | string): string {
|
||||
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
||||
}
|
||||
|
||||
function collectFiles(root: string): string[] {
|
||||
const acc: string[] = [];
|
||||
const walk = (dir: string, prefix: string): void => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
)) {
|
||||
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
walk(full, rel);
|
||||
} else if (entry.isFile() && /\.(yaml|yml|json|md)$/.test(entry.name)) {
|
||||
acc.push(rel);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(root, '');
|
||||
return acc.sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function octal(value: number, width: number): string {
|
||||
return value
|
||||
.toString(8)
|
||||
.padStart(width - 1, '0')
|
||||
.concat('\u0000');
|
||||
}
|
||||
|
||||
function tarHeader(entry: TarEntry): Buffer {
|
||||
const header = Buffer.alloc(512);
|
||||
header.write(entry.name.slice(0, 100), 0, 'utf8');
|
||||
header.write(octal(0o644, 8), 100, 'utf8');
|
||||
header.write(octal(0, 8), 108, 'utf8');
|
||||
header.write(octal(0, 8), 116, 'utf8');
|
||||
header.write(octal(entry.bytes.length, 12), 124, 'utf8');
|
||||
header.write(octal(0, 12), 136, 'utf8');
|
||||
header.write(' ', 148, 'utf8');
|
||||
header.write('0', 156, 'utf8');
|
||||
header.write('ustar\u0000', 257, 'utf8');
|
||||
header.write('00', 263, 'utf8');
|
||||
header.write('bhl', 265, 'utf8');
|
||||
header.write('bhl', 297, 'utf8');
|
||||
let sum = 0;
|
||||
for (const byte of header) {
|
||||
sum += byte;
|
||||
}
|
||||
header.write(octal(sum, 8), 148, 'utf8');
|
||||
return header;
|
||||
}
|
||||
|
||||
function tarBytes(entries: readonly TarEntry[]): Buffer {
|
||||
const parts: Buffer[] = [];
|
||||
for (const entry of entries) {
|
||||
parts.push(tarHeader(entry));
|
||||
parts.push(entry.bytes);
|
||||
const remainder = entry.bytes.length % 512;
|
||||
if (remainder !== 0) {
|
||||
parts.push(Buffer.alloc(512 - remainder));
|
||||
}
|
||||
}
|
||||
parts.push(Buffer.alloc(1024));
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
export function buildRelease(specRoot: string, version: string, outDir: string): ReleaseResult {
|
||||
const diagnostics: { file: string; code: string; message: string }[] = [];
|
||||
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [
|
||||
{ file: specRoot, code: 'bad-version', message: '--version must be a semver string' },
|
||||
],
|
||||
};
|
||||
}
|
||||
let names: string[];
|
||||
try {
|
||||
names = collectFiles(specRoot);
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [{ file: specRoot, code: 'read-error', message: 'spec root is not readable' }],
|
||||
};
|
||||
}
|
||||
if (names.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [
|
||||
{ file: specRoot, code: 'empty-spec', message: 'spec root contains no release files' },
|
||||
],
|
||||
};
|
||||
}
|
||||
const entries: TarEntry[] = names.map((name) => ({
|
||||
name: `bhs-spec-${version}/${name}`,
|
||||
bytes: readFileSync(path.join(specRoot, name)),
|
||||
}));
|
||||
const tarball = tarBytes(entries);
|
||||
const manifest = {
|
||||
schema_version: 1,
|
||||
version,
|
||||
generated_by: 'bhl release',
|
||||
files: entries.map((entry) => ({
|
||||
path: entry.name.replace(`bhs-spec-${version}/`, ''),
|
||||
sha256: sha256(entry.bytes).slice('sha256:'.length),
|
||||
})),
|
||||
};
|
||||
const manifestText = `${JSON.stringify(manifest, null, 2)}\n`;
|
||||
const base = `bhs-spec-${version}`;
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
writeFileSync(path.join(outDir, `${base}.tar`), tarball);
|
||||
writeFileSync(path.join(outDir, `${base}.manifest.json`), manifestText, 'utf8');
|
||||
writeFileSync(
|
||||
path.join(outDir, `${base}.tar.sha256`),
|
||||
`${sha256(tarball).slice('sha256:'.length)} ${base}.tar\n`,
|
||||
'utf8',
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
files: [`${base}.tar`, `${base}.manifest.json`, `${base}.tar.sha256`],
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts');
|
||||
const specRoot = path.join(import.meta.dirname, '..', '..', '..', 'examples', 'synthetic-spec');
|
||||
|
||||
function tmp(t) {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'bhl-release-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
function runRelease(t, version) {
|
||||
const out = tmp(t);
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'release', specRoot, '--version', version, '--out', out],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return { out, code: proc.status, stdout: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
function sha256(file) {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
test('release: tarball детерминирован, manifest сверяется с извлечёнными байтами', (t) => {
|
||||
const first = runRelease(t, '0.1.0');
|
||||
assert.equal(first.code, 0);
|
||||
assert.deepEqual(first.stdout.data.files, [
|
||||
'bhs-spec-0.1.0.tar',
|
||||
'bhs-spec-0.1.0.manifest.json',
|
||||
'bhs-spec-0.1.0.tar.sha256',
|
||||
]);
|
||||
const tarball = path.join(first.out, 'bhs-spec-0.1.0.tar');
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(path.join(first.out, 'bhs-spec-0.1.0.manifest.json'), 'utf8'),
|
||||
);
|
||||
assert.equal(manifest.version, '0.1.0');
|
||||
assert.ok(manifest.files.some((entry) => entry.path === 'CHANGELOG.yaml'));
|
||||
const checksumLine = readFileSync(path.join(first.out, 'bhs-spec-0.1.0.tar.sha256'), 'utf8');
|
||||
assert.equal(checksumLine.split(' ')[0], sha256(tarball), 'сумма tarball совпадает');
|
||||
|
||||
const extract = tmp(t);
|
||||
const untar = spawnSync('tar', ['-xf', tarball, '-C', extract], { encoding: 'utf8' });
|
||||
assert.equal(untar.status, 0, untar.stderr);
|
||||
for (const entry of manifest.files) {
|
||||
const file = path.join(extract, 'bhs-spec-0.1.0', entry.path);
|
||||
assert.equal(sha256(file), entry.sha256, `байты ${entry.path} совпадают с manifest`);
|
||||
}
|
||||
|
||||
const second = runRelease(t, '0.1.0');
|
||||
assert.equal(
|
||||
readFileSync(path.join(second.out, 'bhs-spec-0.1.0.tar'), 'utf8'),
|
||||
readFileSync(tarball, 'utf8'),
|
||||
'повторная сборка идентична байт-в-байт',
|
||||
);
|
||||
});
|
||||
|
||||
test('release: не-semver и лишние аргументы отклоняются', (t) => {
|
||||
const bad = runRelease(t, '0.1');
|
||||
assert.equal(bad.code, 1);
|
||||
assert.equal(bad.stdout.error.code, 'VALIDATION_FAILED');
|
||||
const dir = tmp(t);
|
||||
const usage = spawnSync(process.execPath, [cli, 'release', specRoot, '--version', '1.0.0'], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(usage.status, 2);
|
||||
assert.equal(JSON.parse(usage.stdout).error.code, 'USAGE');
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
Reference in New Issue
Block a user