-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpath.mjs
305 lines (242 loc) · 7.96 KB
/
path.mjs
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
Various tools for FS paths like those used in Posix and Windows.
Only string operations, no IO.
Limitations:
* Not well tested. Expect to delete random files on your disk.
* No support for network paths starting with `\\`.
* No support for `file:` URLs.
* Performance has not been optimized or even benchmarked.
* No support for URL paths. Use `url.mjs` for that.
This module is environment-independent and doesn't detect the current OS.
Default OS-specific instance can be imported from OS-aware module,
namely from `io_deno.mjs`.
*/
import * as l from './lang.mjs'
import * as s from './str.mjs'
export const SEP_WINDOWS = `\\`
export const SEP_POSIX = `/`
/*
Allows strings and custom stringable objects, such as file URLs supported by
Node and Deno. Note that `Paths.prototype.toStr` currently doesn't support
non-strings. We may change that later.
*/
export function isPath(val) {return l.isStr(val) || (l.isObj(val) && l.isScalar(val))}
export function reqPath(val) {return l.req(val, isPath)}
export function optPath(val) {return l.opt(val, isPath)}
export function toPosix(val) {return windows.replaceSep(val, posix.dirSep)}
/*
Collection of functions for manipulating FS paths. Base class used by
OS-specific implementations. Why this is defined as a class:
* Makes it easy to share logic between Windows and Posix variants.
They use overrides without having to pass "options" between functions.
* Makes it possible to implement other variants with a few overrides.
* Makes it possible to monkey-patch.
* Subclasses may choose to be stateful.
Default global instances are exported below.
*/
export class Paths extends l.Emp {
// "Directory separator".
get dirSep() {throw l.errImpl()}
// "Extension separator".
get extSep() {return `.`}
// "Current working directory relative path".
get cwdRel() {return `.`}
// "Parent directory relative path".
get parRel() {return `..`}
// "Current working directory empty value".
get cwdEmp() {return ``}
relPre() {return this.cwdRel + this.dirSep}
// "Volume".
vol() {return ``}
// "Has a volume".
hasVol(val) {return !!this.vol(val)}
isAbs(val) {
val = this.toStr(val)
return this.hasVol(val) || val.startsWith(this.dirSep)
}
isRel(val) {return !this.isAbs(val)}
isRelExplicit(val) {
val = this.toStr(val)
return (
false
|| val === this.cwdRel
|| val === this.parRel
|| val.startsWith(this.cwdRel + this.dirSep)
|| val.startsWith(this.parRel + this.dirSep)
)
}
isRelImplicit(val) {
val = this.toStr(val)
return !this.isAbs(val) && !this.isRelExplicit(val)
}
/*
True if the path ends with a directory separator. When this returns `true`,
the path definitely describes a directory. However, when this returns
`false`, the path may be valid either as a file path or as a directory path.
*/
isDirLike(val) {
val = this.toStr(val)
return this.isCwdRel(val) || val.endsWith(this.dirSep)
}
isRoot(val) {
val = this.toStr(val)
if (val === this.dirSep) return true
const vol = this.vol(val)
return !!vol && (val === vol || val === vol + this.dirSep)
}
// "Is relative path to current working directory".
isCwdRel(val) {
val = this.toStr(val)
return val === this.cwdEmp || val === this.cwdRel || val === this.relPre()
}
clean(val) {return this.cleanPre(this.cleanSuf(val))}
cleanPre(val) {
val = this.toStr(val)
if (this.isCwdRel(val)) return this.cwdEmp
if (this.isAbs(val)) return val
return s.stripPre(val, this.relPre())
}
cleanSuf(val) {
val = this.toStr(val)
if (this.isRoot(val)) return val
return s.stripSuf(val, this.dirSep)
}
// Missing feature: `..` flattening.
join(base, ...vals) {
base = this.clean(base)
for (const src of vals) {
const val = this.clean(src)
if (this.isAbs(val)) {
throw Error(`unable to append absolute path ${l.show(src)} to ${l.show(base)}`)
}
base = s.inter(base, this.dirSep, val)
}
return base
}
// Needs a more specific name because this also returns true if the paths are
// equivalent.
isSubOf(sub, sup) {
sub = this.clean(sub)
sup = this.clean(sup)
return (
true
&& (this.isAbs(sub) === this.isAbs(sup))
&& (
false
|| sub === sup
|| sub.startsWith(this.dirLike(sup))
)
)
}
// Known inefficiency: in the success case, this builds and checks/strips
// the directory prefix twice. TODO tune.
strictRelTo(sub, sup) {
sub = this.clean(sub)
sup = this.clean(sup)
if (!this.isSubOf(sub, sup)) {
throw Error(`unable to make ${l.show(sub)} strictly relative to ${l.show(sup)}: not a subpath`)
}
if (sub === sup) return this.cwdEmp
return s.stripPre(sub, this.dirLike(sup))
}
relTo(sub, sup) {
sub = this.clean(sub)
sup = this.clean(sup)
const subAbs = this.isAbs(sub)
const supAbs = this.isAbs(sup)
if (subAbs !== supAbs) {
throw Error(`unable to make ${l.show(sub)} relative to ${l.show(sup)}: paths must be both absolute or both relative`)
}
const subPath = s.split(sub, this.dirSep)
const supPath = s.split(sup, this.dirSep)
// Length of the common prefix.
let len = 0
while (len < subPath.length && len < supPath.length) {
if (subPath[len] !== supPath[len]) break
len += 1
}
const preLen = supPath.length - len
const sep = this.dirSep
const pre = preLen ? Array(preLen).fill(this.parRel).join(sep) : ``
const suf = subPath.slice(len)
return s.inter(pre, sep, suf.join(sep))
}
/*
Should append the directory separator if the path is non-empty and doesn't
already end with the separator. For other paths, including `.isCwdRel()`,
this should be a nop.
*/
dirLike(val) {return s.optSuf(this.clean(val), this.dirSep)}
dir(val) {
val = this.toStr(val)
if (this.isCwdRel(val)) return this.cwdEmp
if (val.endsWith(this.dirSep)) return this.clean(val)
val = this.clean(val)
if (this.isRoot(val)) return val
const ind = val.lastIndexOf(this.dirSep)
return this.clean(val.slice(0, ind + this.dirSep.length))
}
/*
Usually called "basename" in other libs.
Returns the last dir or file name, including the extension if any.
*/
base(val) {
val = this.clean(val)
if (this.isRoot(val)) return val
const ind = val.lastIndexOf(this.dirSep)
return this.clean(val.slice(ind + this.dirSep.length))
}
// "Extension".
ext(val) {return ext(this.base(val), this.extSep)}
// Returns the part of `base` without an extension.
name(val) {
val = this.base(val)
return s.stripSuf(val, ext(val, this.extSep))
}
replaceSep(val, sep) {
return s.replaceAll(this.toStr(val), this.dirSep, sep)
}
/*
More lax than `l.reqStr`, more strict than `l.render`. Not part of `lang.mjs`
because allowing only this set of inputs is relatively rare.
*/
toStr(val) {
if (l.isStr(val)) return val
if (l.isInst(val, String)) return val.toString()
throw l.errConv(val, `string`)
}
}
export class PathsPosix extends Paths {
get dirSep() {return SEP_POSIX}
}
/*
Known limitations:
* No support for `/`. We simply assume that all FS paths use `\`.
* No support for relative paths with a volume, like `C:path`.
* No support for network paths.
*/
export class PathsWindows extends Paths {
get dirSep() {return SEP_WINDOWS}
vol(val) {
const mat = this.toStr(val).match(/^[A-Za-z]:/)
return (mat && mat[0]) || ``
}
isDirLike(val) {
val = this.toStr(val)
return super.isDirLike(val) || val === this.vol(val)
}
}
/*
Default global instances. The appropriate instance for the current OS must be
chosen by OS-aware modules such as `io_deno.mjs`.
*/
export const posix = new PathsPosix()
export const windows = new PathsWindows()
/* Internal */
// Must be called ONLY on the file name, without the directory path.
function ext(val, sep) {
l.reqStr(val)
l.reqStr(sep)
const ind = val.lastIndexOf(sep)
return ind > 0 ? val.slice(ind) : ``
}