forked from ipfs/js-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathls.js
98 lines (79 loc) · 2.22 KB
/
ls.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict'
const CID = require('cids')
const configure = require('./lib/configure')
const toUrlSearchParams = require('./lib/to-url-search-params')
const stat = require('./files/stat')
module.exports = configure((api, opts) => {
return async function * ls (path, options = {}) {
const pathStr = `${path instanceof Uint8Array ? new CID(path) : path}`
async function mapLink (link) {
let hash = link.Hash
if (hash.includes('/')) {
// the hash is a path, but we need the CID
const ipfsPath = hash.startsWith('/ipfs/') ? hash : `/ipfs/${hash}`
const stats = await stat(opts)(ipfsPath)
hash = stats.cid
}
const entry = {
name: link.Name,
path: pathStr + (link.Name ? `/${link.Name}` : ''),
size: link.Size,
cid: new CID(hash),
type: typeOf(link),
depth: link.Depth || 1
}
if (link.Mode) {
entry.mode = parseInt(link.Mode, 8)
}
if (link.Mtime !== undefined && link.Mtime !== null) {
entry.mtime = {
secs: link.Mtime
}
if (link.MtimeNsecs !== undefined && link.MtimeNsecs !== null) {
entry.mtime.nsecs = link.MtimeNsecs
}
}
return entry
}
const res = await api.post('ls', {
timeout: options.timeout,
signal: options.signal,
searchParams: toUrlSearchParams({
arg: pathStr,
...options
}),
headers: options.headers
})
for await (let result of res.ndjson()) {
result = result.Objects
if (!result) {
throw new Error('expected .Objects in results')
}
result = result[0]
if (!result) {
throw new Error('expected one array in results.Objects')
}
const links = result.Links
if (!Array.isArray(links)) {
throw new Error('expected one array in results.Objects[0].Links')
}
if (!links.length) {
// no links, this is a file, yield a single result
yield mapLink(result)
return
}
yield * links.map(mapLink)
}
}
})
function typeOf (link) {
switch (link.Type) {
case 1:
case 5:
return 'dir'
case 2:
return 'file'
default:
return 'unknown'
}
}