-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
220 lines (191 loc) · 6.08 KB
/
Copy pathindex.js
File metadata and controls
220 lines (191 loc) · 6.08 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// @ts-check
/**
* @import { Stats } from 'node:fs'
*/
'use strict'
const fs = require('fs')
const path = require('path')
const ignore = require('ignore')
const { readdir, lstat } = fs.promises
/**
* PathFilter lets you filter files based on a resolved `filepath`.
* @callback PathFilter
* @param {string} filepath - The resolved `filepath` of the file to test for filtering.
*
* @return {boolean} Return false to filter the given `filepath` and true to include it.
*/
/**
* @type PathFilter
*/
const pathFilter = (/* filepath */) => true
/**
* statFilter lets you filter files based on a lstat object.
* @callback StatFilter
* @param {Stats} st - A fs.Stats instance.
*
* @return {boolean} Return false to filter the given `filepath` and true to include it.
*/
/**
* @type StatFilter
*/
const statFilter = (/* st */) => true
/**
* FWStats is the object that the okdistribute/folder-walker module returns by default.
*
* @typedef FWStats
* @property {string} root - The filepath of the directory where the walk started.
* @property {string} filepath - The resolved assolute path.
* @property {Stats} stat - A fs.Stats instance.
* @property {string} relname - The relative path to `root`.
* @property {string} basename - The resolved filepath of the files containing directory.
*/
/**
* Shaper lets you change the shape of the returned file data from walk-time stats.
* @template T
* @callback Shaper
* @param {FWStats} fwStats - The same status object returned from folder-walker.
*
* @return {T} - Whatever you want returned from the directory walk.
*/
/**
* @type {Shaper<string>}
*/
const shaper = ({ filepath/*, root, stat, relname, basename */ }) => filepath
/**
* AFWReturnType will return the return type of AFW for your given shaper.
*
* @template T
* @typedef {T extends AsyncGenerator<infer U, any, any> ? U : never} AFWReturnType
*/
/**
* Options object.
*
* @template T
* @typedef {object} AFWOpts
* @property {PathFilter} pathFilter=pathFilter - A pathFilter callback.
* @property {StatFilter} statFilter=statFilter - A statFilter callback.
* @property {string[]} ignore=[] - An array of .gitignore style strings of files to ignore.
* @property {number} maxDepth=Infinity - The maximum number of folders to walk down into.
* @property {Shaper<T>} shaper=shaper - A shaper callback.
*/
/**
* Create an async generator that iterates over all folders and directories inside of `dirs`.
*
* @template T
* @public
* @param {string|string[]} dirs - The path or paths of the directory to walk.
* @param {?Partial<AFWOpts<T>>} [opts] - Options used for the directory walk.
* @yields {T} - An iterator that returns a value of type T.
*/
async function * asyncFolderWalker (dirs, opts) {
/** @type {AFWOpts<T>} */
const resolvedOpts = Object.assign({
fs,
pathFilter,
statFilter,
ignore: [],
maxDepth: Infinity,
shaper
}, opts)
// @ts-ignore
const ig = ignore().add(resolvedOpts.ignore)
/** @type {string[]} */
const roots = [dirs].flat().filter(resolvedOpts.pathFilter)
/** @type {string[]} */
const pending = []
while (roots.length) {
const root = roots.shift()
if (!root) continue // Handle potential undefined value
pending.push(root)
while (pending.length) {
const current = pending.shift()
if (!current) continue // Handle potential undefined value
const st = await lstat(current)
const rel = relname(root, current)
if (ig.ignores(st.isDirectory() ? rel + '/' : rel)) continue
if ((!st.isDirectory() || depthLimiter(current, root, resolvedOpts.maxDepth)) && resolvedOpts.statFilter(st)) {
yield resolvedOpts.shaper(fwShape(root, current, st))
continue
}
const files = await readdir(current)
files.sort()
for (const file of files) {
const next = path.join(current, file)
if (resolvedOpts.pathFilter(next)) pending.unshift(next)
}
if (current === root || !resolvedOpts.statFilter(st)) continue
else yield resolvedOpts.shaper(fwShape(root, current, st))
}
}
}
/**
* @param {string} root
* @param {string} name
* @return {string} The basename or relative name if root === name
*/
function relname (root, name) {
return root === name ? path.basename(name) : path.relative(root, name)
}
/**
* Generates the same shape as the folder-walker module.
*
* @param {string} root - Root filepath.
* @param {string} name - Target filepath.
* @param {Stats} st - fs.Stat object.
* @returns {FWStats} Folder walker object.
*/
function fwShape (root, name, st) {
return {
root,
filepath: name,
stat: st,
relname: relname(root, name),
basename: path.basename(name)
}
}
/**
* Test if we are at maximum directory depth.
*
* @param {string} filePath - The resolved path of the target file.
* @param {string} relativeTo - The root directory of the current walk.
* @param {number} maxDepth - The maximum number of folders to descend into.
* @returns {boolean} Return true to signal stop descending.
*/
function depthLimiter (filePath, relativeTo, maxDepth) {
if (maxDepth === Infinity) return false
const rootDepth = relativeTo.split(path.sep).length
const fileDepth = filePath.split(path.sep).length
return fileDepth - rootDepth > maxDepth
}
/**
* Async iterable collector.
*
* @template T
* @public
* @param {AsyncIterableIterator<T>} iterator - The iterator to collect into an array.
* @returns {Promise<T[]>} Array of items collected from the iterator.
*/
async function all (iterator) {
const collect = []
for await (const result of iterator) {
collect.push(result)
}
return collect
}
/**
* Gives you all files from the directory walk as an array.
*
* @template T
* @public
* @param {string|string[]} dirs - The path of the directory to walk, or an array of directory paths.
* @param {Partial<AFWOpts<T>>} [opts] - Options used for the directory walk.
* @returns {Promise<T[]>} Array of files or any other result from the directory walk.
*/
async function allFiles (dirs, opts) {
return all(asyncFolderWalker(dirs, opts))
}
module.exports = {
asyncFolderWalker,
allFiles,
all
}