path.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. 'use strict';
  22. var isWindows = process.platform === 'win32';
  23. var util = require('util');
  24. // resolves . and .. elements in a path array with directory names there
  25. // must be no slashes or device names (c:\) in the array
  26. // (so also no leading and trailing slashes - it does not distinguish
  27. // relative and absolute paths)
  28. function normalizeArray(parts, allowAboveRoot) {
  29. var res = [];
  30. for (var i = 0; i < parts.length; i++) {
  31. var p = parts[i];
  32. // ignore empty parts
  33. if (!p || p === '.')
  34. continue;
  35. if (p === '..') {
  36. if (res.length && res[res.length - 1] !== '..') {
  37. res.pop();
  38. } else if (allowAboveRoot) {
  39. res.push('..');
  40. }
  41. } else {
  42. res.push(p);
  43. }
  44. }
  45. return res;
  46. }
  47. // returns an array with empty elements removed from either end of the input
  48. // array or the original array if no elements need to be removed
  49. function trimArray(arr) {
  50. var lastIndex = arr.length - 1;
  51. var start = 0;
  52. for (; start <= lastIndex; start++) {
  53. if (arr[start])
  54. break;
  55. }
  56. var end = lastIndex;
  57. for (; end >= 0; end--) {
  58. if (arr[end])
  59. break;
  60. }
  61. if (start === 0 && end === lastIndex)
  62. return arr;
  63. if (start > end)
  64. return [];
  65. return arr.slice(start, end + 1);
  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. // Regex to split the tail part of the above into [*, dir, basename, ext]
  72. var splitTailRe =
  73. /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
  74. var win32 = {};
  75. // Function to split a filename into [root, dir, basename, ext]
  76. function win32SplitPath(filename) {
  77. // Separate device+slash from tail
  78. var result = splitDeviceRe.exec(filename),
  79. device = (result[1] || '') + (result[2] || ''),
  80. tail = result[3] || '';
  81. // Split the tail into dir, basename and extension
  82. var result2 = splitTailRe.exec(tail),
  83. dir = result2[1],
  84. basename = result2[2],
  85. ext = result2[3];
  86. return [device, dir, basename, ext];
  87. }
  88. function win32StatPath(path) {
  89. var result = splitDeviceRe.exec(path),
  90. device = result[1] || '',
  91. isUnc = !!device && device[1] !== ':';
  92. return {
  93. device: device,
  94. isUnc: isUnc,
  95. isAbsolute: isUnc || !!result[2], // UNC paths are always absolute
  96. tail: result[3]
  97. };
  98. }
  99. function normalizeUNCRoot(device) {
  100. return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
  101. }
  102. // path.resolve([from ...], to)
  103. win32.resolve = function() {
  104. var resolvedDevice = '',
  105. resolvedTail = '',
  106. resolvedAbsolute = false;
  107. for (var i = arguments.length - 1; i >= -1; i--) {
  108. var path;
  109. if (i >= 0) {
  110. path = arguments[i];
  111. } else if (!resolvedDevice) {
  112. path = process.cwd();
  113. } else {
  114. // Windows has the concept of drive-specific current working
  115. // directories. If we've resolved a drive letter but not yet an
  116. // absolute path, get cwd for that drive. We're sure the device is not
  117. // an unc path at this points, because unc paths are always absolute.
  118. path = process.env['=' + resolvedDevice];
  119. // Verify that a drive-local cwd was found and that it actually points
  120. // to our drive. If not, default to the drive's root.
  121. if (!path || path.substr(0, 3).toLowerCase() !==
  122. resolvedDevice.toLowerCase() + '\\') {
  123. path = resolvedDevice + '\\';
  124. }
  125. }
  126. // Skip empty and invalid entries
  127. if (!util.isString(path)) {
  128. throw new TypeError('Arguments to path.resolve must be strings');
  129. } else if (!path) {
  130. continue;
  131. }
  132. var result = win32StatPath(path),
  133. device = result.device,
  134. isUnc = result.isUnc,
  135. isAbsolute = result.isAbsolute,
  136. tail = result.tail;
  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. if (!resolvedDevice) {
  144. resolvedDevice = device;
  145. }
  146. if (!resolvedAbsolute) {
  147. resolvedTail = tail + '\\' + resolvedTail;
  148. resolvedAbsolute = isAbsolute;
  149. }
  150. if (resolvedDevice && resolvedAbsolute) {
  151. break;
  152. }
  153. }
  154. // Convert slashes to backslashes when `resolvedDevice` points to an UNC
  155. // root. Also squash multiple slashes into a single one where appropriate.
  156. if (isUnc) {
  157. resolvedDevice = normalizeUNCRoot(resolvedDevice);
  158. }
  159. // At this point the path should be resolved to a full absolute path,
  160. // but handle relative paths to be safe (might happen when process.cwd()
  161. // fails)
  162. // Normalize the tail path
  163. resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/),
  164. !resolvedAbsolute).join('\\');
  165. return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
  166. '.';
  167. };
  168. win32.normalize = function(path) {
  169. var result = win32StatPath(path),
  170. device = result.device,
  171. isUnc = result.isUnc,
  172. isAbsolute = result.isAbsolute,
  173. tail = result.tail,
  174. trailingSlash = /[\\\/]$/.test(tail);
  175. // Normalize the tail path
  176. tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\');
  177. if (!tail && !isAbsolute) {
  178. tail = '.';
  179. }
  180. if (tail && trailingSlash) {
  181. tail += '\\';
  182. }
  183. // Convert slashes to backslashes when `device` points to an UNC root.
  184. // Also squash multiple slashes into a single one where appropriate.
  185. if (isUnc) {
  186. device = normalizeUNCRoot(device);
  187. }
  188. return device + (isAbsolute ? '\\' : '') + tail;
  189. };
  190. win32.isAbsolute = function(path) {
  191. return win32StatPath(path).isAbsolute;
  192. };
  193. win32.join = function() {
  194. var paths = [];
  195. for (var i = 0; i < arguments.length; i++) {
  196. var arg = arguments[i];
  197. if (!util.isString(arg)) {
  198. throw new TypeError('Arguments to path.join must be strings');
  199. }
  200. if (arg) {
  201. paths.push(arg);
  202. }
  203. }
  204. var joined = paths.join('\\');
  205. // Make sure that the joined path doesn't start with two slashes, because
  206. // normalize() will mistake it for an UNC path then.
  207. //
  208. // This step is skipped when it is very clear that the user actually
  209. // intended to point at an UNC path. This is assumed when the first
  210. // non-empty string arguments starts with exactly two slashes followed by
  211. // at least one more non-slash character.
  212. //
  213. // Note that for normalize() to treat a path as an UNC path it needs to
  214. // have at least 2 components, so we don't filter for that here.
  215. // This means that the user can use join to construct UNC paths from
  216. // a server name and a share name; for example:
  217. // path.join('//server', 'share') -> '\\\\server\\share\')
  218. if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
  219. joined = joined.replace(/^[\\\/]{2,}/, '\\');
  220. }
  221. return win32.normalize(joined);
  222. };
  223. // path.relative(from, to)
  224. // it will solve the relative path from 'from' to 'to', for instance:
  225. // from = 'C:\\orandea\\test\\aaa'
  226. // to = 'C:\\orandea\\impl\\bbb'
  227. // The output of the function should be: '..\\..\\impl\\bbb'
  228. win32.relative = function(from, to) {
  229. from = win32.resolve(from);
  230. to = win32.resolve(to);
  231. // windows is not case sensitive
  232. var lowerFrom = from.toLowerCase();
  233. var lowerTo = to.toLowerCase();
  234. var toParts = trimArray(to.split('\\'));
  235. var lowerFromParts = trimArray(lowerFrom.split('\\'));
  236. var lowerToParts = trimArray(lowerTo.split('\\'));
  237. var length = Math.min(lowerFromParts.length, lowerToParts.length);
  238. var samePartsLength = length;
  239. for (var i = 0; i < length; i++) {
  240. if (lowerFromParts[i] !== lowerToParts[i]) {
  241. samePartsLength = i;
  242. break;
  243. }
  244. }
  245. if (samePartsLength == 0) {
  246. return to;
  247. }
  248. var outputParts = [];
  249. for (var i = samePartsLength; i < lowerFromParts.length; i++) {
  250. outputParts.push('..');
  251. }
  252. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  253. return outputParts.join('\\');
  254. };
  255. win32._makeLong = function(path) {
  256. // Note: this will *probably* throw somewhere.
  257. if (!util.isString(path))
  258. return path;
  259. if (!path) {
  260. return '';
  261. }
  262. var resolvedPath = win32.resolve(path);
  263. if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
  264. // path is local filesystem path, which needs to be converted
  265. // to long UNC path.
  266. return '\\\\?\\' + resolvedPath;
  267. } else if (/^\\\\[^?.]/.test(resolvedPath)) {
  268. // path is network UNC path, which needs to be converted
  269. // to long UNC path.
  270. return '\\\\?\\UNC\\' + resolvedPath.substring(2);
  271. }
  272. return path;
  273. };
  274. win32.dirname = function(path) {
  275. var result = win32SplitPath(path),
  276. root = result[0],
  277. dir = result[1];
  278. if (!root && !dir) {
  279. // No dirname whatsoever
  280. return '.';
  281. }
  282. if (dir) {
  283. // It has a dirname, strip trailing slash
  284. dir = dir.substr(0, dir.length - 1);
  285. }
  286. return root + dir;
  287. };
  288. win32.basename = function(path, ext) {
  289. var f = win32SplitPath(path)[2];
  290. // TODO: make this comparison case-insensitive on windows?
  291. if (ext && f.substr(-1 * ext.length) === ext) {
  292. f = f.substr(0, f.length - ext.length);
  293. }
  294. return f;
  295. };
  296. win32.extname = function(path) {
  297. return win32SplitPath(path)[3];
  298. };
  299. win32.format = function(pathObject) {
  300. if (!util.isObject(pathObject)) {
  301. throw new TypeError(
  302. "Parameter 'pathObject' must be an object, not " + typeof pathObject
  303. );
  304. }
  305. var root = pathObject.root || '';
  306. if (!util.isString(root)) {
  307. throw new TypeError(
  308. "'pathObject.root' must be a string or undefined, not " +
  309. typeof pathObject.root
  310. );
  311. }
  312. var dir = pathObject.dir;
  313. var base = pathObject.base || '';
  314. if (!dir) {
  315. return base;
  316. }
  317. if (dir[dir.length - 1] === win32.sep) {
  318. return dir + base;
  319. }
  320. return dir + win32.sep + base;
  321. };
  322. win32.parse = function(pathString) {
  323. if (!util.isString(pathString)) {
  324. throw new TypeError(
  325. "Parameter 'pathString' must be a string, not " + typeof pathString
  326. );
  327. }
  328. var allParts = win32SplitPath(pathString);
  329. if (!allParts || allParts.length !== 4) {
  330. throw new TypeError("Invalid path '" + pathString + "'");
  331. }
  332. return {
  333. root: allParts[0],
  334. dir: allParts[0] + allParts[1].slice(0, -1),
  335. base: allParts[2],
  336. ext: allParts[3],
  337. name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
  338. };
  339. };
  340. win32.sep = '\\';
  341. win32.delimiter = ';';
  342. // Split a filename into [root, dir, basename, ext], unix version
  343. // 'root' is just a slash, or nothing.
  344. var splitPathRe =
  345. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  346. var posix = {};
  347. function posixSplitPath(filename) {
  348. return splitPathRe.exec(filename).slice(1);
  349. }
  350. // path.resolve([from ...], to)
  351. // posix version
  352. posix.resolve = function() {
  353. var resolvedPath = '',
  354. resolvedAbsolute = false;
  355. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  356. var path = (i >= 0) ? arguments[i] : process.cwd();
  357. // Skip empty and invalid entries
  358. if (!util.isString(path)) {
  359. throw new TypeError('Arguments to path.resolve must be strings');
  360. } else if (!path) {
  361. continue;
  362. }
  363. resolvedPath = path + '/' + resolvedPath;
  364. resolvedAbsolute = path[0] === '/';
  365. }
  366. // At this point the path should be resolved to a full absolute path, but
  367. // handle relative paths to be safe (might happen when process.cwd() fails)
  368. // Normalize the path
  369. resolvedPath = normalizeArray(resolvedPath.split('/'),
  370. !resolvedAbsolute).join('/');
  371. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  372. };
  373. // path.normalize(path)
  374. // posix version
  375. posix.normalize = function(path) {
  376. var isAbsolute = posix.isAbsolute(path),
  377. trailingSlash = path && path[path.length - 1] === '/';
  378. // Normalize the path
  379. path = normalizeArray(path.split('/'), !isAbsolute).join('/');
  380. if (!path && !isAbsolute) {
  381. path = '.';
  382. }
  383. if (path && trailingSlash) {
  384. path += '/';
  385. }
  386. return (isAbsolute ? '/' : '') + path;
  387. };
  388. // posix version
  389. posix.isAbsolute = function(path) {
  390. return path.charAt(0) === '/';
  391. };
  392. // posix version
  393. posix.join = function() {
  394. var path = '';
  395. for (var i = 0; i < arguments.length; i++) {
  396. var segment = arguments[i];
  397. if (!util.isString(segment)) {
  398. throw new TypeError('Arguments to path.join must be strings');
  399. }
  400. if (segment) {
  401. if (!path) {
  402. path += segment;
  403. } else {
  404. path += '/' + segment;
  405. }
  406. }
  407. }
  408. return posix.normalize(path);
  409. };
  410. // path.relative(from, to)
  411. // posix version
  412. posix.relative = function(from, to) {
  413. from = posix.resolve(from).substr(1);
  414. to = posix.resolve(to).substr(1);
  415. var fromParts = trimArray(from.split('/'));
  416. var toParts = trimArray(to.split('/'));
  417. var length = Math.min(fromParts.length, toParts.length);
  418. var samePartsLength = length;
  419. for (var i = 0; i < length; i++) {
  420. if (fromParts[i] !== toParts[i]) {
  421. samePartsLength = i;
  422. break;
  423. }
  424. }
  425. var outputParts = [];
  426. for (var i = samePartsLength; i < fromParts.length; i++) {
  427. outputParts.push('..');
  428. }
  429. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  430. return outputParts.join('/');
  431. };
  432. posix._makeLong = function(path) {
  433. return path;
  434. };
  435. posix.dirname = function(path) {
  436. var result = posixSplitPath(path),
  437. root = result[0],
  438. dir = result[1];
  439. if (!root && !dir) {
  440. // No dirname whatsoever
  441. return '.';
  442. }
  443. if (dir) {
  444. // It has a dirname, strip trailing slash
  445. dir = dir.substr(0, dir.length - 1);
  446. }
  447. return root + dir;
  448. };
  449. posix.basename = function(path, ext) {
  450. var f = posixSplitPath(path)[2];
  451. // TODO: make this comparison case-insensitive on windows?
  452. if (ext && f.substr(-1 * ext.length) === ext) {
  453. f = f.substr(0, f.length - ext.length);
  454. }
  455. return f;
  456. };
  457. posix.extname = function(path) {
  458. return posixSplitPath(path)[3];
  459. };
  460. posix.format = function(pathObject) {
  461. if (!util.isObject(pathObject)) {
  462. throw new TypeError(
  463. "Parameter 'pathObject' must be an object, not " + typeof pathObject
  464. );
  465. }
  466. var root = pathObject.root || '';
  467. if (!util.isString(root)) {
  468. throw new TypeError(
  469. "'pathObject.root' must be a string or undefined, not " +
  470. typeof pathObject.root
  471. );
  472. }
  473. var dir = pathObject.dir ? pathObject.dir + posix.sep : '';
  474. var base = pathObject.base || '';
  475. return dir + base;
  476. };
  477. posix.parse = function(pathString) {
  478. if (!util.isString(pathString)) {
  479. throw new TypeError(
  480. "Parameter 'pathString' must be a string, not " + typeof pathString
  481. );
  482. }
  483. var allParts = posixSplitPath(pathString);
  484. if (!allParts || allParts.length !== 4) {
  485. throw new TypeError("Invalid path '" + pathString + "'");
  486. }
  487. allParts[1] = allParts[1] || '';
  488. allParts[2] = allParts[2] || '';
  489. allParts[3] = allParts[3] || '';
  490. return {
  491. root: allParts[0],
  492. dir: allParts[0] + allParts[1].slice(0, -1),
  493. base: allParts[2],
  494. ext: allParts[3],
  495. name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
  496. };
  497. };
  498. posix.sep = '/';
  499. posix.delimiter = ':';
  500. if (isWindows)
  501. module.exports = win32;
  502. else /* posix */
  503. module.exports = posix;
  504. module.exports.posix = posix;
  505. module.exports.win32 = win32;