Cotton code
102 lines · 4.2 KB · TypeScriptRaw
#!/usr/bin/env node// Packs a tool fixture directory into a .cottontool the Rust reader accepts:// manifest.json, instructions.md written FROM the manifest (the reader wants// the two byte-identical), tables/<id>.json and pictures/<sha256>.<ext>,// stored uncompressed with no directory entries, no __MACOSX, no .DS_Store.////   node scripts/pack-tool.mjs <fixture dir> <out.cottontool>//// The fixture directory is the one the Rust tests include_str! from// (crates/cotton-tools/tests/fixtures/<tool>/). A records/<table>.json beside// it is the tool's sample rows, packed as records/<table>.json and created// only when the owner imports "with sample rows". A picture file is renamed// to its own sha256 so a manifest "picture": {"photo":"photo:<sha256>"}// matches it.import { createHash } from "node:crypto";import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { join, extname } from "node:path";const [dir, out] = process.argv.slice(2);if (!dir || !out) {  console.error("usage: pack-tool.mjs <fixture dir> <out.cottontool>");  process.exit(2);}const manifestBytes = readFileSync(join(dir, "manifest.json"));const manifest = JSON.parse(manifestBytes.toString("utf8"));const entries = [];entries.push(["manifest.json", manifestBytes]);entries.push(["instructions.md", Buffer.from(manifest.instructions, "utf8")]);// A tool of views over another tool's tables (the kit's Artifacts) has none.let tableFiles = [];try {  tableFiles = readdirSync(join(dir, "tables")).filter((f) => f.endsWith(".json")).sort();} catch {}const listed = new Set(manifest.tables);for (const file of tableFiles) {  const bytes = readFileSync(join(dir, "tables", file));  const id = JSON.parse(bytes.toString("utf8")).id;  if (file !== `${id}.json`) throw new Error(`tables/${file} holds id ${id}`);  if (!listed.has(id)) throw new Error(`tables/${file} is not in manifest.tables`);  entries.push([`tables/${file}`, bytes]);}let records = [];try {  records = readdirSync(join(dir, "records")).filter((f) => f.endsWith(".json")).sort();} catch {}for (const file of records) {  const id = file.slice(0, -".json".length);  if (!listed.has(id)) throw new Error(`records/${file} is not a table in manifest.tables`);  entries.push([`records/${file}`, readFileSync(join(dir, "records", file))]);}let pictures = [];try {  pictures = readdirSync(join(dir, "pictures")).filter((f) => !f.startsWith("."));} catch {}for (const file of pictures.sort()) {  const bytes = readFileSync(join(dir, "pictures", file));  const sha = createHash("sha256").update(bytes).digest("hex");  entries.push([`pictures/${sha}${extname(file).toLowerCase()}`, bytes]);}// A minimal zip writer: local headers + central directory, method 0 (store).const crcTable = new Uint32Array(256).map((_, n) => {  let c = n;  for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;  return c >>> 0;});const crc32 = (buf) => {  let c = 0xffffffff;  for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);  return (c ^ 0xffffffff) >>> 0;};const u16 = (n) => { const b = Buffer.alloc(2); b.writeUInt16LE(n); return b; };const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32LE(n >>> 0); return b; };const locals = [];const centrals = [];let offset = 0;for (const [name, bytes] of entries) {  const nameBytes = Buffer.from(name, "utf8");  const crc = crc32(bytes);  const local = Buffer.concat([    u32(0x04034b50), u16(20), u16(0x0800), u16(0), u16(0), u16(0),    u32(crc), u32(bytes.length), u32(bytes.length), u16(nameBytes.length), u16(0), nameBytes, bytes,  ]);  centrals.push(Buffer.concat([    u32(0x02014b50), u16(20), u16(20), u16(0x0800), u16(0), u16(0), u16(0),    u32(crc), u32(bytes.length), u32(bytes.length), u16(nameBytes.length), u16(0), u16(0), u16(0), u16(0),    u32(0), u32(offset), nameBytes,  ]));  locals.push(local);  offset += local.length;}const central = Buffer.concat(centrals);const end = Buffer.concat([  u32(0x06054b50), u16(0), u16(0), u16(entries.length), u16(entries.length),  u32(central.length), u32(offset), u16(0),]);writeFileSync(out, Buffer.concat([...locals, central, end]));console.log(`${out}: ${entries.map(([n]) => n).join(", ")} (${statSync(out).size} bytes)`);