/
path.ts
81 lines (62 loc) · 1.79 KB
/
path.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
export const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
export const relativePath = /^\.?\.\//;
export function isAbsolute(path: string) {
return absolutePath.test(path);
}
export function isRelative(path: string) {
return relativePath.test(path);
}
export function normalize(path: string) {
return path.replace(/\\/g, '/');
}
export function basename(path: string) {
return path.split(/(\/|\\)/).pop();
}
export function dirname(path: string) {
const match = /(\/|\\)[^/\\]*$/.exec(path);
if (!match) return '.';
const dir = path.slice(0, -match[0].length);
// If `dir` is the empty string, we're at root.
return dir ? dir : '/';
}
export function extname(path: string) {
const match = /\.[^.]+$/.exec(basename(path) as string);
if (!match) return '';
return match[0];
}
export function relative(from: string, to: string) {
const fromParts = from.split(/[/\\]/).filter(Boolean);
const toParts = to.split(/[/\\]/).filter(Boolean);
if (fromParts[0] === '.') fromParts.shift();
if (toParts[0] === '.') toParts.shift();
while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
while (toParts[0] === '..' && fromParts.length > 0) {
toParts.shift();
fromParts.pop();
}
while (fromParts.pop()) {
toParts.unshift('..');
}
return toParts.join('/');
}
export function resolve(...paths: string[]) {
let resolvedParts = (paths.shift() as string).split(/[/\\]/);
paths.forEach(path => {
if (isAbsolute(path)) {
resolvedParts = path.split(/[/\\]/);
} else {
const parts = path.split(/[/\\]/);
while (parts[0] === '.' || parts[0] === '..') {
const part = parts.shift();
if (part === '..') {
resolvedParts.pop();
}
}
resolvedParts.push.apply(resolvedParts, parts);
}
});
return resolvedParts.join('/');
}