Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80738 views
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
var _path = require('path');
24
25
// we are new enough we already have this from the system, just export the
26
// system then
27
if (_path.posix) {
28
module.exports = _path;
29
return;
30
}
31
32
var isWindows = process.platform === 'win32';
33
var util = require('util');
34
35
36
// resolves . and .. elements in a path array with directory names there
37
// must be no slashes, empty elements, or device names (c:\) in the array
38
// (so also no leading and trailing slashes - it does not distinguish
39
// relative and absolute paths)
40
function normalizeArray(parts, allowAboveRoot) {
41
// if the path tries to go above the root, `up` ends up > 0
42
var up = 0;
43
for (var i = parts.length - 1; i >= 0; i--) {
44
var last = parts[i];
45
if (last === '.') {
46
parts.splice(i, 1);
47
} else if (last === '..') {
48
parts.splice(i, 1);
49
up++;
50
} else if (up) {
51
parts.splice(i, 1);
52
up--;
53
}
54
}
55
56
// if the path is allowed to go above the root, restore leading ..s
57
if (allowAboveRoot) {
58
for (; up--; up) {
59
parts.unshift('..');
60
}
61
}
62
63
return parts;
64
}
65
66
67
// Regex to split a windows path into three parts: [*, device, slash,
68
// tail] windows-only
69
var splitDeviceRe =
70
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
71
72
// Regex to split the tail part of the above into [*, dir, basename, ext]
73
var splitTailRe =
74
/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
75
76
var normalizeUNCRoot = function(device) {
77
return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
78
};
79
80
81
var win32 = {};
82
83
// Function to split a filename into [root, dir, basename, ext]
84
win32.splitPath = function(filename) {
85
// Separate device+slash from tail
86
var result = splitDeviceRe.exec(filename),
87
device = (result[1] || '') + (result[2] || ''),
88
tail = result[3] || '';
89
// Split the tail into dir, basename and extension
90
var result2 = splitTailRe.exec(tail),
91
dir = result2[1],
92
basename = result2[2],
93
ext = result2[3];
94
return [device, dir, basename, ext];
95
};
96
97
98
// path.resolve([from ...], to)
99
win32.resolve = function() {
100
var resolvedDevice = '',
101
resolvedTail = '',
102
resolvedAbsolute = false;
103
104
for (var i = arguments.length - 1; i >= -1; i--) {
105
var path;
106
if (i >= 0) {
107
path = arguments[i];
108
} else if (!resolvedDevice) {
109
path = process.cwd();
110
} else {
111
// Windows has the concept of drive-specific current working
112
// directories. If we've resolved a drive letter but not yet an
113
// absolute path, get cwd for that drive. We're sure the device is not
114
// an unc path at this points, because unc paths are always absolute.
115
path = process.env['=' + resolvedDevice];
116
// Verify that a drive-local cwd was found and that it actually points
117
// to our drive. If not, default to the drive's root.
118
if (!path || path.substr(0, 3).toLowerCase() !==
119
resolvedDevice.toLowerCase() + '\\') {
120
path = resolvedDevice + '\\';
121
}
122
}
123
124
// Skip empty and invalid entries
125
if (typeof path !== 'string') {
126
throw new TypeError('Arguments to path.resolve must be strings');
127
} else if (!path) {
128
continue;
129
}
130
131
var result = splitDeviceRe.exec(path),
132
device = result[1] || '',
133
isUnc = device && device.charAt(1) !== ':',
134
isAbsolute = win32.isAbsolute(path),
135
tail = result[3];
136
137
if (device &&
138
resolvedDevice &&
139
device.toLowerCase() !== resolvedDevice.toLowerCase()) {
140
// This path points to another device so it is not applicable
141
continue;
142
}
143
144
if (!resolvedDevice) {
145
resolvedDevice = device;
146
}
147
if (!resolvedAbsolute) {
148
resolvedTail = tail + '\\' + resolvedTail;
149
resolvedAbsolute = isAbsolute;
150
}
151
152
if (resolvedDevice && resolvedAbsolute) {
153
break;
154
}
155
}
156
157
// Convert slashes to backslashes when `resolvedDevice` points to an UNC
158
// root. Also squash multiple slashes into a single one where appropriate.
159
if (isUnc) {
160
resolvedDevice = normalizeUNCRoot(resolvedDevice);
161
}
162
163
// At this point the path should be resolved to a full absolute path,
164
// but handle relative paths to be safe (might happen when process.cwd()
165
// fails)
166
167
// Normalize the tail path
168
169
function f(p) {
170
return !!p;
171
}
172
173
resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),
174
!resolvedAbsolute).join('\\');
175
176
return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
177
'.';
178
};
179
180
181
win32.normalize = function(path) {
182
var result = splitDeviceRe.exec(path),
183
device = result[1] || '',
184
isUnc = device && device.charAt(1) !== ':',
185
isAbsolute = win32.isAbsolute(path),
186
tail = result[3],
187
trailingSlash = /[\\\/]$/.test(tail);
188
189
// If device is a drive letter, we'll normalize to lower case.
190
if (device && device.charAt(1) === ':') {
191
device = device[0].toLowerCase() + device.substr(1);
192
}
193
194
// Normalize the tail path
195
tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) {
196
return !!p;
197
}), !isAbsolute).join('\\');
198
199
if (!tail && !isAbsolute) {
200
tail = '.';
201
}
202
if (tail && trailingSlash) {
203
tail += '\\';
204
}
205
206
// Convert slashes to backslashes when `device` points to an UNC root.
207
// Also squash multiple slashes into a single one where appropriate.
208
if (isUnc) {
209
device = normalizeUNCRoot(device);
210
}
211
212
return device + (isAbsolute ? '\\' : '') + tail;
213
};
214
215
216
win32.isAbsolute = function(path) {
217
var result = splitDeviceRe.exec(path),
218
device = result[1] || '',
219
isUnc = device && device.charAt(1) !== ':';
220
// UNC paths are always absolute
221
return !!result[2] || isUnc;
222
};
223
224
225
win32.join = function() {
226
function f(p) {
227
if (typeof p !== 'string') {
228
throw new TypeError('Arguments to path.join must be strings');
229
}
230
return p;
231
}
232
233
var paths = Array.prototype.filter.call(arguments, f);
234
var joined = paths.join('\\');
235
236
// Make sure that the joined path doesn't start with two slashes, because
237
// normalize() will mistake it for an UNC path then.
238
//
239
// This step is skipped when it is very clear that the user actually
240
// intended to point at an UNC path. This is assumed when the first
241
// non-empty string arguments starts with exactly two slashes followed by
242
// at least one more non-slash character.
243
//
244
// Note that for normalize() to treat a path as an UNC path it needs to
245
// have at least 2 components, so we don't filter for that here.
246
// This means that the user can use join to construct UNC paths from
247
// a server name and a share name; for example:
248
// path.join('//server', 'share') -> '\\\\server\\share\')
249
if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
250
joined = joined.replace(/^[\\\/]{2,}/, '\\');
251
}
252
253
return win32.normalize(joined);
254
};
255
256
257
// path.relative(from, to)
258
// it will solve the relative path from 'from' to 'to', for instance:
259
// from = 'C:\\orandea\\test\\aaa'
260
// to = 'C:\\orandea\\impl\\bbb'
261
// The output of the function should be: '..\\..\\impl\\bbb'
262
win32.relative = function(from, to) {
263
from = win32.resolve(from);
264
to = win32.resolve(to);
265
266
// windows is not case sensitive
267
var lowerFrom = from.toLowerCase();
268
var lowerTo = to.toLowerCase();
269
270
function trim(arr) {
271
var start = 0;
272
for (; start < arr.length; start++) {
273
if (arr[start] !== '') break;
274
}
275
276
var end = arr.length - 1;
277
for (; end >= 0; end--) {
278
if (arr[end] !== '') break;
279
}
280
281
if (start > end) return [];
282
return arr.slice(start, end - start + 1);
283
}
284
285
var toParts = trim(to.split('\\'));
286
287
var lowerFromParts = trim(lowerFrom.split('\\'));
288
var lowerToParts = trim(lowerTo.split('\\'));
289
290
var length = Math.min(lowerFromParts.length, lowerToParts.length);
291
var samePartsLength = length;
292
for (var i = 0; i < length; i++) {
293
if (lowerFromParts[i] !== lowerToParts[i]) {
294
samePartsLength = i;
295
break;
296
}
297
}
298
299
if (samePartsLength == 0) {
300
return to;
301
}
302
303
var outputParts = [];
304
for (var i = samePartsLength; i < lowerFromParts.length; i++) {
305
outputParts.push('..');
306
}
307
308
outputParts = outputParts.concat(toParts.slice(samePartsLength));
309
310
return outputParts.join('\\');
311
};
312
313
314
win32._makeLong = function(path) {
315
// Note: this will *probably* throw somewhere.
316
if (typeof path !== 'string')
317
return path;
318
319
if (!path) {
320
return '';
321
}
322
323
var resolvedPath = win32.resolve(path);
324
325
if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
326
// path is local filesystem path, which needs to be converted
327
// to long UNC path.
328
return '\\\\?\\' + resolvedPath;
329
} else if (/^\\\\[^?.]/.test(resolvedPath)) {
330
// path is network UNC path, which needs to be converted
331
// to long UNC path.
332
return '\\\\?\\UNC\\' + resolvedPath.substring(2);
333
}
334
335
return path;
336
};
337
338
339
win32.dirname = function(path) {
340
var result = win32.splitPath(path),
341
root = result[0],
342
dir = result[1];
343
344
if (!root && !dir) {
345
// No dirname whatsoever
346
return '.';
347
}
348
349
if (dir) {
350
// It has a dirname, strip trailing slash
351
dir = dir.substr(0, dir.length - 1);
352
}
353
354
return root + dir;
355
};
356
357
358
win32.basename = function(path, ext) {
359
var f = win32.splitPath(path)[2];
360
// TODO: make this comparison case-insensitive on windows?
361
if (ext && f.substr(-1 * ext.length) === ext) {
362
f = f.substr(0, f.length - ext.length);
363
}
364
return f;
365
};
366
367
368
win32.extname = function(path) {
369
return win32.splitPath(path)[3];
370
};
371
372
373
win32.sep = '\\';
374
win32.delimiter = ';';
375
376
377
// Split a filename into [root, dir, basename, ext], unix version
378
// 'root' is just a slash, or nothing.
379
var splitPathRe =
380
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
381
var posix = {};
382
383
384
posix.splitPath = function(filename) {
385
return splitPathRe.exec(filename).slice(1);
386
};
387
388
389
// path.resolve([from ...], to)
390
// posix version
391
posix.resolve = function() {
392
var resolvedPath = '',
393
resolvedAbsolute = false;
394
395
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
396
var path = (i >= 0) ? arguments[i] : process.cwd();
397
398
// Skip empty and invalid entries
399
if (typeof path !== 'string') {
400
throw new TypeError('Arguments to path.resolve must be strings');
401
} else if (!path) {
402
continue;
403
}
404
405
resolvedPath = path + '/' + resolvedPath;
406
resolvedAbsolute = path.charAt(0) === '/';
407
}
408
409
// At this point the path should be resolved to a full absolute path, but
410
// handle relative paths to be safe (might happen when process.cwd() fails)
411
412
// Normalize the path
413
resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
414
return !!p;
415
}), !resolvedAbsolute).join('/');
416
417
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
418
};
419
420
// path.normalize(path)
421
// posix version
422
posix.normalize = function(path) {
423
var isAbsolute = posix.isAbsolute(path),
424
trailingSlash = path.substr(-1) === '/';
425
426
// Normalize the path
427
path = normalizeArray(path.split('/').filter(function(p) {
428
return !!p;
429
}), !isAbsolute).join('/');
430
431
if (!path && !isAbsolute) {
432
path = '.';
433
}
434
if (path && trailingSlash) {
435
path += '/';
436
}
437
438
return (isAbsolute ? '/' : '') + path;
439
};
440
441
// posix version
442
posix.isAbsolute = function(path) {
443
return path.charAt(0) === '/';
444
};
445
446
// posix version
447
posix.join = function() {
448
var paths = Array.prototype.slice.call(arguments, 0);
449
return posix.normalize(paths.filter(function(p, index) {
450
if (typeof p !== 'string') {
451
throw new TypeError('Arguments to path.join must be strings');
452
}
453
return p;
454
}).join('/'));
455
};
456
457
458
// path.relative(from, to)
459
// posix version
460
posix.relative = function(from, to) {
461
from = posix.resolve(from).substr(1);
462
to = posix.resolve(to).substr(1);
463
464
function trim(arr) {
465
var start = 0;
466
for (; start < arr.length; start++) {
467
if (arr[start] !== '') break;
468
}
469
470
var end = arr.length - 1;
471
for (; end >= 0; end--) {
472
if (arr[end] !== '') break;
473
}
474
475
if (start > end) return [];
476
return arr.slice(start, end - start + 1);
477
}
478
479
var fromParts = trim(from.split('/'));
480
var toParts = trim(to.split('/'));
481
482
var length = Math.min(fromParts.length, toParts.length);
483
var samePartsLength = length;
484
for (var i = 0; i < length; i++) {
485
if (fromParts[i] !== toParts[i]) {
486
samePartsLength = i;
487
break;
488
}
489
}
490
491
var outputParts = [];
492
for (var i = samePartsLength; i < fromParts.length; i++) {
493
outputParts.push('..');
494
}
495
496
outputParts = outputParts.concat(toParts.slice(samePartsLength));
497
498
return outputParts.join('/');
499
};
500
501
502
posix._makeLong = function(path) {
503
return path;
504
};
505
506
507
posix.dirname = function(path) {
508
var result = posix.splitPath(path),
509
root = result[0],
510
dir = result[1];
511
512
if (!root && !dir) {
513
// No dirname whatsoever
514
return '.';
515
}
516
517
if (dir) {
518
// It has a dirname, strip trailing slash
519
dir = dir.substr(0, dir.length - 1);
520
}
521
522
return root + dir;
523
};
524
525
526
posix.basename = function(path, ext) {
527
var f = posix.splitPath(path)[2];
528
// TODO: make this comparison case-insensitive on windows?
529
if (ext && f.substr(-1 * ext.length) === ext) {
530
f = f.substr(0, f.length - ext.length);
531
}
532
return f;
533
};
534
535
536
posix.extname = function(path) {
537
return posix.splitPath(path)[3];
538
};
539
540
541
posix.sep = '/';
542
posix.delimiter = ':';
543
544
545
var splitPath;
546
if (isWindows) {
547
splitPath = win32.splitPath;
548
module.exports = win32;
549
} else /* posix */ {
550
splitPath = posix.splitPath;
551
module.exports = posix;
552
}
553
554
555
module.exports.posix = posix;
556
module.exports.win32 = win32;
557
558