forked from ipld/codec-fixtures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-fixtures.js
78 lines (73 loc) · 2.17 KB
/
make-fixtures.js
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
import fs from 'fs/promises'
import path from 'path'
import { sha256 } from 'multiformats/hashes/sha2'
import * as Block from 'multiformats/block'
import { garbage } from 'ipld-garbage'
import { codecs } from './codecs.js'
const fixturesDir = new URL('../fixtures/', import.meta.url)
const fixturesSrcDir = new URL('../_fixtures_src/', import.meta.url)
async function makeGarbage () {
for (let i = 0; i < 25;) {
const value = garbage(5000)
const block = await Block.encode({ value, codec: codecs['dag-cbor'].codec, hasher: sha256 })
if (block.bytes.length < 1000) {
continue
}
await fs.writeFile(new URL(`./garbage-${i.toString().padStart(2, '0')}.dag-cbor`, fixturesSrcDir), block.bytes)
i++
}
}
async function makeFixtures () {
await Promise.all((await fs.readdir(fixturesSrcDir)).map(async (file) => {
const furl = new URL(file, fixturesSrcDir)
const stat = await fs.stat(furl)
if (!stat.isFile()) {
return
}
const ext = path.extname(file).slice(1)
if (!codecs[ext]) {
console.error(`Unknown extension for file '${file}'`)
return
}
const name = file.substring(0, file.length - ext.length - 1)
const bytes = await fs.readFile(furl)
let value
try {
value = codecs[ext].codec.decode(bytes)
} catch (err) {
console.error(`Failed to decode fixture ${file}`)
throw err
}
const fdir = new URL(`./${name}/`, fixturesDir)
try {
await fs.mkdir(fdir)
} catch (err) {
if (err.code !== 'EEXIST') {
throw err
}
}
for (const { codec, complete } of Object.values(codecs)) {
let block
try {
block = await Block.encode({ value, codec, hasher: sha256 })
} catch (err) {
if (!complete) { // failure is allowed, this codec can't handle this form
continue
}
throw err
}
await fs.writeFile(new URL(`./${block.cid.toString()}.${codec.name}`, fdir), block.bytes)
}
}))
}
if (process.argv.includes('--garbage')) {
makeGarbage().catch((err) => {
console.error(err)
process.exit(1)
})
} else {
makeFixtures().catch((err) => {
console.error(err)
process.exit(1)
})
}