1 // Copyright Joyent, Inc. and other Node contributors.
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:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
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.
23 var isWindows = process.platform === 'win32';
24 var util = require('util');
27 // resolves . and .. elements in a path array with directory names there
28 // must be no slashes, empty elements, or device names (c:\) in the array
29 // (so also no leading and trailing slashes - it does not distinguish
30 // relative and absolute paths)
31 function normalizeArray(parts, allowAboveRoot) {
32 // if the path tries to go above the root, `up` ends up > 0
34 for (var i = parts.length - 1; i >= 0; i--) {
38 } else if (last === '..') {
47 // if the path is allowed to go above the root, restore leading ..s
59 // Regex to split a windows path into three parts: [*, device, slash,
62 /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
64 // Regex to split the tail part of the above into [*, dir, basename, ext]
66 /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
68 // Function to split a filename into [root, dir, basename, ext]
70 var splitPath = function(filename) {
71 // Separate device+slash from tail
72 var result = splitDeviceRe.exec(filename),
73 device = (result[1] || '') + (result[2] || ''),
74 tail = result[3] || '';
75 // Split the tail into dir, basename and extension
76 var result2 = splitTailRe.exec(tail),
78 basename = result2[2],
80 return [device, dir, basename, ext];
83 var normalizeUNCRoot = function(device) {
84 return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
87 // path.resolve([from ...], to)
89 exports.resolve = function() {
90 var resolvedDevice = '',
92 resolvedAbsolute = false;
94 for (var i = arguments.length - 1; i >= -1; i--) {
98 } else if (!resolvedDevice) {
101 // Windows has the concept of drive-specific current working
102 // directories. If we've resolved a drive letter but not yet an
103 // absolute path, get cwd for that drive. We're sure the device is not
104 // an unc path at this points, because unc paths are always absolute.
105 path = process.env['=' + resolvedDevice];
106 // Verify that a drive-local cwd was found and that it actually points
107 // to our drive. If not, default to the drive's root.
108 if (!path || path.substr(0, 3).toLowerCase() !==
109 resolvedDevice.toLowerCase() + '\\') {
110 path = resolvedDevice + '\\';
114 // Skip empty and invalid entries
115 if (!util.isString(path)) {
116 throw new TypeError('Arguments to path.resolve must be strings');
121 var result = splitDeviceRe.exec(path),
122 device = result[1] || '',
123 isUnc = device && device.charAt(1) !== ':',
124 isAbsolute = exports.isAbsolute(path),
129 device.toLowerCase() !== resolvedDevice.toLowerCase()) {
130 // This path points to another device so it is not applicable
134 if (!resolvedDevice) {
135 resolvedDevice = device;
137 if (!resolvedAbsolute) {
138 resolvedTail = tail + '\\' + resolvedTail;
139 resolvedAbsolute = isAbsolute;
142 if (resolvedDevice && resolvedAbsolute) {
147 // Convert slashes to backslashes when `resolvedDevice` points to an UNC
148 // root. Also squash multiple slashes into a single one where appropriate.
150 resolvedDevice = normalizeUNCRoot(resolvedDevice);
153 // At this point the path should be resolved to a full absolute path,
154 // but handle relative paths to be safe (might happen when process.cwd()
157 // Normalize the tail path
163 resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),
164 !resolvedAbsolute).join('\\');
166 // If device is a drive letter, we'll normalize to lower case.
167 if (resolvedDevice && resolvedDevice.charAt(1) === ':') {
168 resolvedDevice = resolvedDevice[0].toLowerCase() +
169 resolvedDevice.substr(1);
172 return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
177 exports.normalize = function(path) {
178 var result = splitDeviceRe.exec(path),
179 device = result[1] || '',
180 isUnc = device && device.charAt(1) !== ':',
181 isAbsolute = exports.isAbsolute(path),
183 trailingSlash = /[\\\/]$/.test(tail);
185 // If device is a drive letter, we'll normalize to lower case.
186 if (device && device.charAt(1) === ':') {
187 device = device[0].toLowerCase() + device.substr(1);
190 // Normalize the tail path
191 tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) {
193 }), !isAbsolute).join('\\');
195 if (!tail && !isAbsolute) {
198 if (tail && trailingSlash) {
202 // Convert slashes to backslashes when `device` points to an UNC root.
203 // Also squash multiple slashes into a single one where appropriate.
205 device = normalizeUNCRoot(device);
208 return device + (isAbsolute ? '\\' : '') + tail;
212 exports.isAbsolute = function(path) {
213 var result = splitDeviceRe.exec(path),
214 device = result[1] || '',
215 isUnc = !!device && device.charAt(1) !== ':';
216 // UNC paths are always absolute
217 return !!result[2] || isUnc;
221 exports.join = function() {
223 if (!util.isString(p)) {
224 throw new TypeError('Arguments to path.join must be strings');
229 var paths = Array.prototype.filter.call(arguments, f);
230 var joined = paths.join('\\');
232 // Make sure that the joined path doesn't start with two slashes, because
233 // normalize() will mistake it for an UNC path then.
235 // This step is skipped when it is very clear that the user actually
236 // intended to point at an UNC path. This is assumed when the first
237 // non-empty string arguments starts with exactly two slashes followed by
238 // at least one more non-slash character.
240 // Note that for normalize() to treat a path as an UNC path it needs to
241 // have at least 2 components, so we don't filter for that here.
242 // This means that the user can use join to construct UNC paths from
243 // a server name and a share name; for example:
244 // path.join('//server', 'share') -> '\\\\server\\share\')
245 if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
246 joined = joined.replace(/^[\\\/]{2,}/, '\\');
249 return exports.normalize(joined);
252 // path.relative(from, to)
253 // it will solve the relative path from 'from' to 'to', for instance:
254 // from = 'C:\\orandea\\test\\aaa'
255 // to = 'C:\\orandea\\impl\\bbb'
256 // The output of the function should be: '..\\..\\impl\\bbb'
258 exports.relative = function(from, to) {
259 from = exports.resolve(from);
260 to = exports.resolve(to);
262 // windows is not case sensitive
263 var lowerFrom = from.toLowerCase();
264 var lowerTo = to.toLowerCase();
268 for (; start < arr.length; start++) {
269 if (arr[start] !== '') break;
272 var end = arr.length - 1;
273 for (; end >= 0; end--) {
274 if (arr[end] !== '') break;
277 if (start > end) return [];
278 return arr.slice(start, end + 1);
281 var toParts = trim(to.split('\\'));
283 var lowerFromParts = trim(lowerFrom.split('\\'));
284 var lowerToParts = trim(lowerTo.split('\\'));
286 var length = Math.min(lowerFromParts.length, lowerToParts.length);
287 var samePartsLength = length;
288 for (var i = 0; i < length; i++) {
289 if (lowerFromParts[i] !== lowerToParts[i]) {
295 if (samePartsLength == 0) {
299 var outputParts = [];
300 for (var i = samePartsLength; i < lowerFromParts.length; i++) {
301 outputParts.push('..');
304 outputParts = outputParts.concat(toParts.slice(samePartsLength));
306 return outputParts.join('\\');
310 exports.delimiter = ';';
314 // Split a filename into [root, dir, basename, ext], unix version
315 // 'root' is just a slash, or nothing.
317 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
318 var splitPath = function(filename) {
319 return splitPathRe.exec(filename).slice(1);
322 // path.resolve([from ...], to)
324 exports.resolve = function() {
325 var resolvedPath = '',
326 resolvedAbsolute = false;
328 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
329 var path = (i >= 0) ? arguments[i] : process.cwd();
331 // Skip empty and invalid entries
332 if (!util.isString(path)) {
333 throw new TypeError('Arguments to path.resolve must be strings');
338 resolvedPath = path + '/' + resolvedPath;
339 resolvedAbsolute = path.charAt(0) === '/';
342 // At this point the path should be resolved to a full absolute path, but
343 // handle relative paths to be safe (might happen when process.cwd() fails)
345 // Normalize the path
346 resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
348 }), !resolvedAbsolute).join('/');
350 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
353 // path.normalize(path)
355 exports.normalize = function(path) {
356 var isAbsolute = exports.isAbsolute(path),
357 trailingSlash = path[path.length - 1] === '/',
358 segments = path.split('/'),
359 nonEmptySegments = [];
361 // Normalize the path
362 for (var i = 0; i < segments.length; i++) {
364 nonEmptySegments.push(segments[i]);
367 path = normalizeArray(nonEmptySegments, !isAbsolute).join('/');
369 if (!path && !isAbsolute) {
372 if (path && trailingSlash) {
376 return (isAbsolute ? '/' : '') + path;
380 exports.isAbsolute = function(path) {
381 return path.charAt(0) === '/';
385 exports.join = function() {
387 for (var i = 0; i < arguments.length; i++) {
388 var segment = arguments[i];
389 if (!util.isString(segment)) {
390 throw new TypeError('Arguments to path.join must be strings');
396 path += '/' + segment;
400 return exports.normalize(path);
404 // path.relative(from, to)
406 exports.relative = function(from, to) {
407 from = exports.resolve(from).substr(1);
408 to = exports.resolve(to).substr(1);
412 for (; start < arr.length; start++) {
413 if (arr[start] !== '') break;
416 var end = arr.length - 1;
417 for (; end >= 0; end--) {
418 if (arr[end] !== '') break;
421 if (start > end) return [];
422 return arr.slice(start, end + 1);
425 var fromParts = trim(from.split('/'));
426 var toParts = trim(to.split('/'));
428 var length = Math.min(fromParts.length, toParts.length);
429 var samePartsLength = length;
430 for (var i = 0; i < length; i++) {
431 if (fromParts[i] !== toParts[i]) {
437 var outputParts = [];
438 for (var i = samePartsLength; i < fromParts.length; i++) {
439 outputParts.push('..');
442 outputParts = outputParts.concat(toParts.slice(samePartsLength));
444 return outputParts.join('/');
448 exports.delimiter = ':';
451 exports.dirname = function(path) {
452 var result = splitPath(path),
457 // No dirname whatsoever
462 // It has a dirname, strip trailing slash
463 dir = dir.substr(0, dir.length - 1);
470 exports.basename = function(path, ext) {
471 var f = splitPath(path)[2];
472 // TODO: make this comparison case-insensitive on windows?
473 if (ext && f.substr(-1 * ext.length) === ext) {
474 f = f.substr(0, f.length - ext.length);
480 exports.extname = function(path) {
481 return splitPath(path)[3];
485 exports.exists = util.deprecate(function(path, callback) {
486 require('fs').exists(path, callback);
487 }, 'path.exists is now called `fs.exists`.');
490 exports.existsSync = util.deprecate(function(path) {
491 return require('fs').existsSync(path);
492 }, 'path.existsSync is now called `fs.existsSync`.');
496 exports._makeLong = function(path) {
497 // Note: this will *probably* throw somewhere.
498 if (!util.isString(path))
505 var resolvedPath = exports.resolve(path);
507 if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
508 // path is local filesystem path, which needs to be converted
510 return '\\\\?\\' + resolvedPath;
511 } else if (/^\\\\[^?.]/.test(resolvedPath)) {
512 // path is network UNC path, which needs to be converted
514 return '\\\\?\\UNC\\' + resolvedPath.substring(2);
520 exports._makeLong = function(path) {