path.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. // Adapted version of:
  22. // https://github.com/joyent/node/blob/v0.11.3/lib/path.js
  23. // Shim process global from node.
  24. var process = Object.create(require('../system'));
  25. process.cwd = process.pathFor.bind(process, 'CurProcD');
  26. // Update original check in node `process.platform === 'win32'` since in SDK it's `winnt`.
  27. var isWindows = process.platform.indexOf('win') === 0;
  28. // resolves . and .. elements in a path array with directory names there
  29. // must be no slashes, empty elements, or device names (c:\) in the array
  30. // (so also no leading and trailing slashes - it does not distinguish
  31. // relative and absolute paths)
  32. function normalizeArray(parts, allowAboveRoot) {
  33. // if the path tries to go above the root, `up` ends up > 0
  34. var up = 0;
  35. for (var i = parts.length - 1; i >= 0; i--) {
  36. var last = parts[i];
  37. if (last === '.') {
  38. parts.splice(i, 1);
  39. } else if (last === '..') {
  40. parts.splice(i, 1);
  41. up++;
  42. } else if (up) {
  43. parts.splice(i, 1);
  44. up--;
  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. return parts;
  54. }
  55. if (isWindows) {
  56. // Regex to split a windows path into three parts: [*, device, slash,
  57. // tail] windows-only
  58. var splitDeviceRe =
  59. /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  60. // Regex to split the tail part of the above into [*, dir, basename, ext]
  61. var splitTailRe =
  62. /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
  63. // Function to split a filename into [root, dir, basename, ext]
  64. // windows version
  65. var splitPath = function(filename) {
  66. // Separate device+slash from tail
  67. var result = splitDeviceRe.exec(filename),
  68. device = (result[1] || '') + (result[2] || ''),
  69. tail = result[3] || '';
  70. // Split the tail into dir, basename and extension
  71. var result2 = splitTailRe.exec(tail),
  72. dir = result2[1],
  73. basename = result2[2],
  74. ext = result2[3];
  75. return [device, dir, basename, ext];
  76. };
  77. var normalizeUNCRoot = function(device) {
  78. return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
  79. };
  80. // path.resolve([from ...], to)
  81. // windows version
  82. exports.resolve = function() {
  83. var resolvedDevice = '',
  84. resolvedTail = '',
  85. resolvedAbsolute = false;
  86. for (var i = arguments.length - 1; i >= -1; i--) {
  87. var path;
  88. if (i >= 0) {
  89. path = arguments[i];
  90. } else if (!resolvedDevice) {
  91. path = process.cwd();
  92. } else {
  93. // Windows has the concept of drive-specific current working
  94. // directories. If we've resolved a drive letter but not yet an
  95. // absolute path, get cwd for that drive. We're sure the device is not
  96. // an unc path at this points, because unc paths are always absolute.
  97. path = process.env['=' + resolvedDevice];
  98. // Verify that a drive-local cwd was found and that it actually points
  99. // to our drive. If not, default to the drive's root.
  100. if (!path || path.substr(0, 3).toLowerCase() !==
  101. resolvedDevice.toLowerCase() + '\\') {
  102. path = resolvedDevice + '\\';
  103. }
  104. }
  105. // Skip empty and invalid entries
  106. if (typeof path !== 'string') {
  107. throw new TypeError('Arguments to path.resolve must be strings');
  108. } else if (!path) {
  109. continue;
  110. }
  111. var result = splitDeviceRe.exec(path),
  112. device = result[1] || '',
  113. isUnc = device && device.charAt(1) !== ':',
  114. isAbsolute = exports.isAbsolute(path),
  115. tail = result[3];
  116. if (device &&
  117. resolvedDevice &&
  118. device.toLowerCase() !== resolvedDevice.toLowerCase()) {
  119. // This path points to another device so it is not applicable
  120. continue;
  121. }
  122. if (!resolvedDevice) {
  123. resolvedDevice = device;
  124. }
  125. if (!resolvedAbsolute) {
  126. resolvedTail = tail + '\\' + resolvedTail;
  127. resolvedAbsolute = isAbsolute;
  128. }
  129. if (resolvedDevice && resolvedAbsolute) {
  130. break;
  131. }
  132. }
  133. // Convert slashes to backslashes when `resolvedDevice` points to an UNC
  134. // root. Also squash multiple slashes into a single one where appropriate.
  135. if (isUnc) {
  136. resolvedDevice = normalizeUNCRoot(resolvedDevice);
  137. }
  138. // At this point the path should be resolved to a full absolute path,
  139. // but handle relative paths to be safe (might happen when process.cwd()
  140. // fails)
  141. // Normalize the tail path
  142. function f(p) {
  143. return !!p;
  144. }
  145. resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f),
  146. !resolvedAbsolute).join('\\');
  147. return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
  148. '.';
  149. };
  150. // windows version
  151. exports.normalize = function(path) {
  152. var result = splitDeviceRe.exec(path),
  153. device = result[1] || '',
  154. isUnc = device && device.charAt(1) !== ':',
  155. isAbsolute = exports.isAbsolute(path),
  156. tail = result[3],
  157. trailingSlash = /[\\\/]$/.test(tail);
  158. // If device is a drive letter, we'll normalize to lower case.
  159. if (device && device.charAt(1) === ':') {
  160. device = device[0].toLowerCase() + device.substr(1);
  161. }
  162. // Normalize the tail path
  163. tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) {
  164. return !!p;
  165. }), !isAbsolute).join('\\');
  166. if (!tail && !isAbsolute) {
  167. tail = '.';
  168. }
  169. if (tail && trailingSlash) {
  170. tail += '\\';
  171. }
  172. // Convert slashes to backslashes when `device` points to an UNC root.
  173. // Also squash multiple slashes into a single one where appropriate.
  174. if (isUnc) {
  175. device = normalizeUNCRoot(device);
  176. }
  177. return device + (isAbsolute ? '\\' : '') + tail;
  178. };
  179. // windows version
  180. exports.isAbsolute = function(path) {
  181. var result = splitDeviceRe.exec(path),
  182. device = result[1] || '',
  183. isUnc = device && device.charAt(1) !== ':';
  184. // UNC paths are always absolute
  185. return !!result[2] || isUnc;
  186. };
  187. // windows version
  188. exports.join = function() {
  189. function f(p) {
  190. if (typeof p !== 'string') {
  191. throw new TypeError('Arguments to path.join must be strings');
  192. }
  193. return p;
  194. }
  195. var paths = Array.prototype.filter.call(arguments, f);
  196. var joined = paths.join('\\');
  197. // Make sure that the joined path doesn't start with two slashes, because
  198. // normalize() will mistake it for an UNC path then.
  199. //
  200. // This step is skipped when it is very clear that the user actually
  201. // intended to point at an UNC path. This is assumed when the first
  202. // non-empty string arguments starts with exactly two slashes followed by
  203. // at least one more non-slash character.
  204. //
  205. // Note that for normalize() to treat a path as an UNC path it needs to
  206. // have at least 2 components, so we don't filter for that here.
  207. // This means that the user can use join to construct UNC paths from
  208. // a server name and a share name; for example:
  209. // path.join('//server', 'share') -> '\\\\server\\share\')
  210. if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
  211. joined = joined.replace(/^[\\\/]{2,}/, '\\');
  212. }
  213. return exports.normalize(joined);
  214. };
  215. // path.relative(from, to)
  216. // it will solve the relative path from 'from' to 'to', for instance:
  217. // from = 'C:\\orandea\\test\\aaa'
  218. // to = 'C:\\orandea\\impl\\bbb'
  219. // The output of the function should be: '..\\..\\impl\\bbb'
  220. // windows version
  221. exports.relative = function(from, to) {
  222. from = exports.resolve(from);
  223. to = exports.resolve(to);
  224. // windows is not case sensitive
  225. var lowerFrom = from.toLowerCase();
  226. var lowerTo = to.toLowerCase();
  227. function trim(arr) {
  228. var start = 0;
  229. for (; start < arr.length; start++) {
  230. if (arr[start] !== '') break;
  231. }
  232. var end = arr.length - 1;
  233. for (; end >= 0; end--) {
  234. if (arr[end] !== '') break;
  235. }
  236. if (start > end) return [];
  237. return arr.slice(start, end - start + 1);
  238. }
  239. var toParts = trim(to.split('\\'));
  240. var lowerFromParts = trim(lowerFrom.split('\\'));
  241. var lowerToParts = trim(lowerTo.split('\\'));
  242. var length = Math.min(lowerFromParts.length, lowerToParts.length);
  243. var samePartsLength = length;
  244. for (var i = 0; i < length; i++) {
  245. if (lowerFromParts[i] !== lowerToParts[i]) {
  246. samePartsLength = i;
  247. break;
  248. }
  249. }
  250. if (samePartsLength == 0) {
  251. return to;
  252. }
  253. var outputParts = [];
  254. for (var i = samePartsLength; i < lowerFromParts.length; i++) {
  255. outputParts.push('..');
  256. }
  257. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  258. return outputParts.join('\\');
  259. };
  260. exports.sep = '\\';
  261. exports.delimiter = ';';
  262. } else /* posix */ {
  263. // Split a filename into [root, dir, basename, ext], unix version
  264. // 'root' is just a slash, or nothing.
  265. var splitPathRe =
  266. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  267. var splitPath = function(filename) {
  268. return splitPathRe.exec(filename).slice(1);
  269. };
  270. // path.resolve([from ...], to)
  271. // posix version
  272. exports.resolve = function() {
  273. var resolvedPath = '',
  274. resolvedAbsolute = false;
  275. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  276. var path = (i >= 0) ? arguments[i] : process.cwd();
  277. // Skip empty and invalid entries
  278. if (typeof path !== 'string') {
  279. throw new TypeError('Arguments to path.resolve must be strings');
  280. } else if (!path) {
  281. continue;
  282. }
  283. resolvedPath = path + '/' + resolvedPath;
  284. resolvedAbsolute = path.charAt(0) === '/';
  285. }
  286. // At this point the path should be resolved to a full absolute path, but
  287. // handle relative paths to be safe (might happen when process.cwd() fails)
  288. // Normalize the path
  289. resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
  290. return !!p;
  291. }), !resolvedAbsolute).join('/');
  292. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  293. };
  294. // path.normalize(path)
  295. // posix version
  296. exports.normalize = function(path) {
  297. var isAbsolute = exports.isAbsolute(path),
  298. trailingSlash = path.substr(-1) === '/';
  299. // Normalize the path
  300. path = normalizeArray(path.split('/').filter(function(p) {
  301. return !!p;
  302. }), !isAbsolute).join('/');
  303. if (!path && !isAbsolute) {
  304. path = '.';
  305. }
  306. if (path && trailingSlash) {
  307. path += '/';
  308. }
  309. return (isAbsolute ? '/' : '') + path;
  310. };
  311. // posix version
  312. exports.isAbsolute = function(path) {
  313. return path.charAt(0) === '/';
  314. };
  315. // posix version
  316. exports.join = function() {
  317. var paths = Array.prototype.slice.call(arguments, 0);
  318. return exports.normalize(paths.filter(function(p, index) {
  319. if (typeof p !== 'string') {
  320. throw new TypeError('Arguments to path.join must be strings');
  321. }
  322. return p;
  323. }).join('/'));
  324. };
  325. // path.relative(from, to)
  326. // posix version
  327. exports.relative = function(from, to) {
  328. from = exports.resolve(from).substr(1);
  329. to = exports.resolve(to).substr(1);
  330. function trim(arr) {
  331. var start = 0;
  332. for (; start < arr.length; start++) {
  333. if (arr[start] !== '') break;
  334. }
  335. var end = arr.length - 1;
  336. for (; end >= 0; end--) {
  337. if (arr[end] !== '') break;
  338. }
  339. if (start > end) return [];
  340. return arr.slice(start, end - start + 1);
  341. }
  342. var fromParts = trim(from.split('/'));
  343. var toParts = trim(to.split('/'));
  344. var length = Math.min(fromParts.length, toParts.length);
  345. var samePartsLength = length;
  346. for (var i = 0; i < length; i++) {
  347. if (fromParts[i] !== toParts[i]) {
  348. samePartsLength = i;
  349. break;
  350. }
  351. }
  352. var outputParts = [];
  353. for (var i = samePartsLength; i < fromParts.length; i++) {
  354. outputParts.push('..');
  355. }
  356. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  357. return outputParts.join('/');
  358. };
  359. exports.sep = '/';
  360. exports.delimiter = ':';
  361. }
  362. exports.dirname = function(path) {
  363. var result = splitPath(path),
  364. root = result[0],
  365. dir = result[1];
  366. if (!root && !dir) {
  367. // No dirname whatsoever
  368. return '.';
  369. }
  370. if (dir) {
  371. // It has a dirname, strip trailing slash
  372. dir = dir.substr(0, dir.length - 1);
  373. }
  374. return root + dir;
  375. };
  376. exports.basename = function(path, ext) {
  377. var f = splitPath(path)[2];
  378. // TODO: make this comparison case-insensitive on windows?
  379. if (ext && f.substr(-1 * ext.length) === ext) {
  380. f = f.substr(0, f.length - ext.length);
  381. }
  382. return f;
  383. };
  384. exports.extname = function(path) {
  385. return splitPath(path)[3];
  386. };
  387. if (isWindows) {
  388. exports._makeLong = function(path) {
  389. // Note: this will *probably* throw somewhere.
  390. if (typeof path !== 'string')
  391. return path;
  392. if (!path) {
  393. return '';
  394. }
  395. var resolvedPath = exports.resolve(path);
  396. if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
  397. // path is local filesystem path, which needs to be converted
  398. // to long UNC path.
  399. return '\\\\?\\' + resolvedPath;
  400. } else if (/^\\\\[^?.]/.test(resolvedPath)) {
  401. // path is network UNC path, which needs to be converted
  402. // to long UNC path.
  403. return '\\\\?\\UNC\\' + resolvedPath.substring(2);
  404. }
  405. return path;
  406. };
  407. } else {
  408. exports._makeLong = function(path) {
  409. return path;
  410. };
  411. }