6af430ec478ac3a282055bdd7508f64ac42c6f72
[platform/upstream/nodejs.git] / lib / path.js
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 isWindows = process.platform === 'win32';
24 var util = require('util');
25
26
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
33   var up = 0;
34   for (var i = parts.length - 1; i >= 0; i--) {
35     var last = parts[i];
36     if (last === '.') {
37       parts.splice(i, 1);
38     } else if (last === '..') {
39       parts.splice(i, 1);
40       up++;
41     } else if (up) {
42       parts.splice(i, 1);
43       up--;
44     }
45   }
46
47   // if the path is allowed to go above the root, restore leading ..s
48   if (allowAboveRoot) {
49     for (; up--; up) {
50       parts.unshift('..');
51     }
52   }
53
54   return parts;
55 }
56
57
58 if (isWindows) {
59   // Regex to split a windows path into three parts: [*, device, slash,
60   // tail] windows-only
61   var splitDeviceRe =
62       /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
63
64   // Regex to split the tail part of the above into [*, dir, basename, ext]
65   var splitTailRe =
66       /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
67
68   // Function to split a filename into [root, dir, basename, ext]
69   // windows version
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),
77         dir = result2[1],
78         basename = result2[2],
79         ext = result2[3];
80     return [device, dir, basename, ext];
81   };
82
83   var normalizeUNCRoot = function(device) {
84     return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
85   };
86
87   // path.resolve([from ...], to)
88   // windows version
89   exports.resolve = function() {
90     var resolvedDevice = '',
91         resolvedTail = '',
92         resolvedAbsolute = false;
93
94     for (var i = arguments.length - 1; i >= -1; i--) {
95       var path;
96       if (i >= 0) {
97         path = arguments[i];
98       } else if (!resolvedDevice) {
99         path = process.cwd();
100       } else {
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 + '\\';
111         }
112       }
113
114       // Skip empty and invalid entries
115       if (!util.isString(path)) {
116         throw new TypeError('Arguments to path.resolve must be strings');
117       } else if (!path) {
118         continue;
119       }
120
121       var result = splitDeviceRe.exec(path),
122           device = result[1] || '',
123           isUnc = device && device.charAt(1) !== ':',
124           isAbsolute = exports.isAbsolute(path),
125           tail = result[3];
126
127       if (device &&
128           resolvedDevice &&
129           device.toLowerCase() !== resolvedDevice.toLowerCase()) {
130         // This path points to another device so it is not applicable
131         continue;
132       }
133
134       if (!resolvedDevice) {
135         resolvedDevice = device;
136       }
137       if (!resolvedAbsolute) {
138         resolvedTail = tail + '\\' + resolvedTail;
139         resolvedAbsolute = isAbsolute;
140       }
141
142       if (resolvedDevice && resolvedAbsolute) {
143         break;
144       }
145     }
146
147     // Convert slashes to backslashes when `resolvedDevice` points to an UNC
148     // root. Also squash multiple slashes into a single one where appropriate.
149     if (isUnc) {
150       resolvedDevice = normalizeUNCRoot(resolvedDevice);
151     }
152
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()
155     // fails)
156
157     // Normalize the tail path
158
159     function f(p) {
160       return !!p;
161     }
162
163     resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),
164                                   !resolvedAbsolute).join('\\');
165
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);
170     }
171
172     return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
173            '.';
174   };
175
176   // windows version
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),
182         tail = result[3],
183         trailingSlash = /[\\\/]$/.test(tail);
184
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);
188     }
189
190     // Normalize the tail path
191     tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) {
192       return !!p;
193     }), !isAbsolute).join('\\');
194
195     if (!tail && !isAbsolute) {
196       tail = '.';
197     }
198     if (tail && trailingSlash) {
199       tail += '\\';
200     }
201
202     // Convert slashes to backslashes when `device` points to an UNC root.
203     // Also squash multiple slashes into a single one where appropriate.
204     if (isUnc) {
205       device = normalizeUNCRoot(device);
206     }
207
208     return device + (isAbsolute ? '\\' : '') + tail;
209   };
210
211   // windows version
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;
218   };
219
220   // windows version
221   exports.join = function() {
222     function f(p) {
223       if (!util.isString(p)) {
224         throw new TypeError('Arguments to path.join must be strings');
225       }
226       return p;
227     }
228
229     var paths = Array.prototype.filter.call(arguments, f);
230     var joined = paths.join('\\');
231
232     // Make sure that the joined path doesn't start with two slashes, because
233     // normalize() will mistake it for an UNC path then.
234     //
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.
239     //
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,}/, '\\');
247     }
248
249     return exports.normalize(joined);
250   };
251
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'
257   // windows version
258   exports.relative = function(from, to) {
259     from = exports.resolve(from);
260     to = exports.resolve(to);
261
262     // windows is not case sensitive
263     var lowerFrom = from.toLowerCase();
264     var lowerTo = to.toLowerCase();
265
266     function trim(arr) {
267       var start = 0;
268       for (; start < arr.length; start++) {
269         if (arr[start] !== '') break;
270       }
271
272       var end = arr.length - 1;
273       for (; end >= 0; end--) {
274         if (arr[end] !== '') break;
275       }
276
277       if (start > end) return [];
278       return arr.slice(start, end + 1);
279     }
280
281     var toParts = trim(to.split('\\'));
282
283     var lowerFromParts = trim(lowerFrom.split('\\'));
284     var lowerToParts = trim(lowerTo.split('\\'));
285
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]) {
290         samePartsLength = i;
291         break;
292       }
293     }
294
295     if (samePartsLength == 0) {
296       return to;
297     }
298
299     var outputParts = [];
300     for (var i = samePartsLength; i < lowerFromParts.length; i++) {
301       outputParts.push('..');
302     }
303
304     outputParts = outputParts.concat(toParts.slice(samePartsLength));
305
306     return outputParts.join('\\');
307   };
308
309   exports.sep = '\\';
310   exports.delimiter = ';';
311
312 } else /* posix */ {
313
314   // Split a filename into [root, dir, basename, ext], unix version
315   // 'root' is just a slash, or nothing.
316   var splitPathRe =
317       /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
318   var splitPath = function(filename) {
319     return splitPathRe.exec(filename).slice(1);
320   };
321
322   // path.resolve([from ...], to)
323   // posix version
324   exports.resolve = function() {
325     var resolvedPath = '',
326         resolvedAbsolute = false;
327
328     for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
329       var path = (i >= 0) ? arguments[i] : process.cwd();
330
331       // Skip empty and invalid entries
332       if (!util.isString(path)) {
333         throw new TypeError('Arguments to path.resolve must be strings');
334       } else if (!path) {
335         continue;
336       }
337
338       resolvedPath = path + '/' + resolvedPath;
339       resolvedAbsolute = path.charAt(0) === '/';
340     }
341
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)
344
345     // Normalize the path
346     resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
347       return !!p;
348     }), !resolvedAbsolute).join('/');
349
350     return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
351   };
352
353   // path.normalize(path)
354   // posix version
355   exports.normalize = function(path) {
356     var isAbsolute = exports.isAbsolute(path),
357         trailingSlash = path[path.length - 1] === '/',
358         segments = path.split('/'),
359         nonEmptySegments = [];
360
361     // Normalize the path
362     for (var i = 0; i < segments.length; i++) {
363       if (segments[i]) {
364         nonEmptySegments.push(segments[i]);
365       }
366     }
367     path = normalizeArray(nonEmptySegments, !isAbsolute).join('/');
368
369     if (!path && !isAbsolute) {
370       path = '.';
371     }
372     if (path && trailingSlash) {
373       path += '/';
374     }
375
376     return (isAbsolute ? '/' : '') + path;
377   };
378
379   // posix version
380   exports.isAbsolute = function(path) {
381     return path.charAt(0) === '/';
382   };
383
384   // posix version
385   exports.join = function() {
386     var path = '';
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');
391       }
392       if (segment) {
393         if (!path) {
394           path += segment;
395         } else {
396           path += '/' + segment;
397         }
398       }
399     }
400     return exports.normalize(path);
401   };
402
403
404   // path.relative(from, to)
405   // posix version
406   exports.relative = function(from, to) {
407     from = exports.resolve(from).substr(1);
408     to = exports.resolve(to).substr(1);
409
410     function trim(arr) {
411       var start = 0;
412       for (; start < arr.length; start++) {
413         if (arr[start] !== '') break;
414       }
415
416       var end = arr.length - 1;
417       for (; end >= 0; end--) {
418         if (arr[end] !== '') break;
419       }
420
421       if (start > end) return [];
422       return arr.slice(start, end + 1);
423     }
424
425     var fromParts = trim(from.split('/'));
426     var toParts = trim(to.split('/'));
427
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]) {
432         samePartsLength = i;
433         break;
434       }
435     }
436
437     var outputParts = [];
438     for (var i = samePartsLength; i < fromParts.length; i++) {
439       outputParts.push('..');
440     }
441
442     outputParts = outputParts.concat(toParts.slice(samePartsLength));
443
444     return outputParts.join('/');
445   };
446
447   exports.sep = '/';
448   exports.delimiter = ':';
449 }
450
451 exports.dirname = function(path) {
452   var result = splitPath(path),
453       root = result[0],
454       dir = result[1];
455
456   if (!root && !dir) {
457     // No dirname whatsoever
458     return '.';
459   }
460
461   if (dir) {
462     // It has a dirname, strip trailing slash
463     dir = dir.substr(0, dir.length - 1);
464   }
465
466   return root + dir;
467 };
468
469
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);
475   }
476   return f;
477 };
478
479
480 exports.extname = function(path) {
481   return splitPath(path)[3];
482 };
483
484
485 exports.exists = util.deprecate(function(path, callback) {
486   require('fs').exists(path, callback);
487 }, 'path.exists is now called `fs.exists`.');
488
489
490 exports.existsSync = util.deprecate(function(path) {
491   return require('fs').existsSync(path);
492 }, 'path.existsSync is now called `fs.existsSync`.');
493
494
495 if (isWindows) {
496   exports._makeLong = function(path) {
497     // Note: this will *probably* throw somewhere.
498     if (!util.isString(path))
499       return path;
500
501     if (!path) {
502       return '';
503     }
504
505     var resolvedPath = exports.resolve(path);
506
507     if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
508       // path is local filesystem path, which needs to be converted
509       // to long UNC path.
510       return '\\\\?\\' + resolvedPath;
511     } else if (/^\\\\[^?.]/.test(resolvedPath)) {
512       // path is network UNC path, which needs to be converted
513       // to long UNC path.
514       return '\\\\?\\UNC\\' + resolvedPath.substring(2);
515     }
516
517     return path;
518   };
519 } else {
520   exports._makeLong = function(path) {
521     return path;
522   };
523 }