forked from ipfs-inactive/js-ipfs-unixfs-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat-to-shard.js
74 lines (67 loc) · 1.63 KB
/
flat-to-shard.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
'use strict'
const waterfall = require('async/waterfall')
const DirSharded = require('./dir-sharded')
module.exports = flatToShard
function flatToShard (child, dir, threshold, options, callback) {
maybeFlatToShardOne(dir, threshold, options, (err, newDir) => {
if (err) {
callback(err)
return // early
}
const parent = newDir.parent
if (parent) {
waterfall([
(callback) => {
if (newDir !== dir) {
if (child) {
child.parent = newDir
}
parent.put(newDir.parentKey, newDir, callback)
} else {
callback()
}
},
(callback) => {
if (parent) {
flatToShard(newDir, parent, threshold, options, callback)
} else {
callback(null, newDir)
}
}
], callback)
} else {
// no parent, we're done climbing tree
callback(null, newDir)
}
})
}
function maybeFlatToShardOne (dir, threshold, options, callback) {
if (dir.flat && dir.directChildrenCount() >= threshold) {
definitelyShardOne(dir, options, callback)
} else {
callback(null, dir)
}
}
function definitelyShardOne (oldDir, options, callback) {
const newDir = DirSharded({
root: oldDir.root,
dir: true,
parent: oldDir.parent,
parentKey: oldDir.parentKey,
path: oldDir.path,
dirty: oldDir.dirty,
flat: false
}, options)
oldDir.eachChildSeries(
(key, value, callback) => {
newDir.put(key, value, callback)
},
(err) => {
if (err) {
callback(err)
} else {
callback(err, newDir)
}
}
)
}