3
3
const CID = require ( 'cids' )
4
4
const configure = require ( './lib/configure' )
5
5
const toUrlSearchParams = require ( './lib/to-url-search-params' )
6
+ const stat = require ( './files/stat' )
6
7
7
- module . exports = configure ( api => {
8
+ module . exports = configure ( ( api , opts ) => {
8
9
return async function * ls ( path , options = { } ) {
10
+ const pathStr = `${ path instanceof Uint8Array ? new CID ( path ) : path } `
11
+
12
+ async function mapLink ( link ) {
13
+ let hash = link . Hash
14
+
15
+ if ( hash . includes ( '/' ) ) {
16
+ // the hash is a path, but we need the CID
17
+ const ipfsPath = hash . startsWith ( '/ipfs/' ) ? hash : `/ipfs/${ hash } `
18
+ const stats = await stat ( opts ) ( ipfsPath )
19
+
20
+ hash = stats . cid
21
+ }
22
+
23
+ const entry = {
24
+ name : link . Name ,
25
+ path : pathStr + ( link . Name ? `/${ link . Name } ` : '' ) ,
26
+ size : link . Size ,
27
+ cid : new CID ( hash ) ,
28
+ type : typeOf ( link ) ,
29
+ depth : link . Depth || 1
30
+ }
31
+
32
+ if ( link . Mode ) {
33
+ entry . mode = parseInt ( link . Mode , 8 )
34
+ }
35
+
36
+ if ( link . Mtime !== undefined && link . Mtime !== null ) {
37
+ entry . mtime = {
38
+ secs : link . Mtime
39
+ }
40
+
41
+ if ( link . MtimeNsecs !== undefined && link . MtimeNsecs !== null ) {
42
+ entry . mtime . nsecs = link . MtimeNsecs
43
+ }
44
+ }
45
+
46
+ return entry
47
+ }
48
+
9
49
const res = await api . post ( 'ls' , {
10
50
timeout : options . timeout ,
11
51
signal : options . signal ,
12
52
searchParams : toUrlSearchParams ( {
13
- arg : ` ${ path instanceof Uint8Array ? new CID ( path ) : path } ` ,
53
+ arg : pathStr ,
14
54
...options
15
55
} ) ,
16
56
headers : options . headers
@@ -28,37 +68,19 @@ module.exports = configure(api => {
28
68
throw new Error ( 'expected one array in results.Objects' )
29
69
}
30
70
31
- result = result . Links
32
- if ( ! Array . isArray ( result ) ) {
71
+ const links = result . Links
72
+ if ( ! Array . isArray ( links ) ) {
33
73
throw new Error ( 'expected one array in results.Objects[0].Links' )
34
74
}
35
75
36
- for ( const link of result ) {
37
- const entry = {
38
- name : link . Name ,
39
- path : path + '/' + link . Name ,
40
- size : link . Size ,
41
- cid : new CID ( link . Hash ) ,
42
- type : typeOf ( link ) ,
43
- depth : link . Depth || 1
44
- }
76
+ if ( ! links . length ) {
77
+ // no links, this is a file, yield a single result
78
+ yield mapLink ( result )
45
79
46
- if ( link . Mode ) {
47
- entry . mode = parseInt ( link . Mode , 8 )
48
- }
49
-
50
- if ( link . Mtime !== undefined && link . Mtime !== null ) {
51
- entry . mtime = {
52
- secs : link . Mtime
53
- }
54
-
55
- if ( link . MtimeNsecs !== undefined && link . MtimeNsecs !== null ) {
56
- entry . mtime . nsecs = link . MtimeNsecs
57
- }
58
- }
59
-
60
- yield entry
80
+ return
61
81
}
82
+
83
+ yield * links . map ( mapLink )
62
84
}
63
85
}
64
86
} )
0 commit comments