UNPKG

2.77 kBJavaScriptView Raw
1'use strict';
2
3var FS = require('fs'),
4 PATH = require('path');
5for(var i in PATH) exports[i] = PATH[i];
6
7var isWindows = exports.isWindows = process.platform === 'win32',
8 dirSep = exports.dirSep = isWindows? '\\' : '/',
9 dirSepRe = exports.dirSepRe = isWindows? '\\\\' : '/';
10exports.pathSep = isWindows? ';' : ':';
11
12exports.isAbsolute = function(path) {
13 var re = new RegExp('^([a-zA-Z]:)?' + dirSepRe);
14 return path.match(re);
15};
16
17exports.isRoot = function(path) {
18 var re = new RegExp('^([a-zA-Z]:)?' + dirSepRe + '$');
19 return path.match(re);
20};
21
22/**
23 * Extension to the PATH.relative() function to add `./` to the
24 * start of relative path if `dot` flag equals to `true`.
25 *
26 * @param {String} from
27 * @param {String} to
28 * @param {Boolean} dot
29 * @return {String}
30 */
31exports.relative = function(from, to, dot) {
32 var path = PATH.relative(from, to);
33 if (dot && !new RegExp('^\\.{1,2}' + dirSepRe).test(path)) {
34 path = '.' + dirSep + path;
35 }
36 return path;
37};
38
39exports.absolute = function(path, startDir) {
40 return exports.isAbsolute(path) ?
41 path :
42 exports.normalize(exports.join(startDir || process.cwd(), path));
43};
44
45exports.unixToOs = function(path) {
46 return path.replace(/\//g, dirSep);
47};
48
49exports.joinPosix = function() {
50 var paths = Array.prototype.slice.call(arguments, 0);
51 return exports.normalizePosix(paths.filter(function(p) {
52 return p && typeof p === 'string';
53 }).join('/'));
54};
55
56exports.normalizePosix = function(path) {
57 var isAbsolute = path.charAt(0) === '/',
58 trailingSlash = path.slice(-1) === '/';
59
60 // Normalize the path
61 path = normalizeArray(path
62 .split('/')
63 .filter(function(p) {
64 return !!p;
65 }), !isAbsolute).join('/');
66
67 if (!path && !isAbsolute) {
68 path = '.';
69 }
70 if (path && trailingSlash) {
71 path += '/';
72 }
73
74 return (isAbsolute ? '/' : '') + path;
75};
76
77// Support compatability with node 0.6.x and remove warnings on node 0.8.x
78exports.exists = FS.exists || PATH.exists;
79exports.existsSync = FS.existsSync || PATH.existsSync;
80
81function normalizeArray(parts, allowAboveRoot) {
82 // if the path tries to go above the root, `up` ends up > 0
83 var up = 0;
84 for (var i = parts.length - 1; i >= 0; i--) {
85 var last = parts[i];
86 if (last === '.') {
87 parts.splice(i, 1);
88 } else if (last === '..') {
89 parts.splice(i, 1);
90 up++;
91 } else if (up) {
92 parts.splice(i, 1);
93 up--;
94 }
95 }
96
97 // if the path is allowed to go above the root, restore leading ..s
98 if (allowAboveRoot) {
99 for (; up--; up) {
100 parts.unshift('..');
101 }
102 }
103
104 return parts;
105}