-
Notifications
You must be signed in to change notification settings - Fork 6
/
util.ts
102 lines (82 loc) · 2.07 KB
/
util.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const normalizeArray = (parts: string[], allowAboveRoot: boolean) => {
const res = [];
for (let i = 0; i < parts.length; i++) {
const p = parts[i];
// ignore empty parts
if (!p || p === '.')
continue;
if (p === '..') {
if (res.length && res[res.length - 1] !== '..') {
res.pop();
} else if (allowAboveRoot) {
res.push('..');
}
} else {
res.push(p);
}
}
return res;
}
const trimArray = (arr: any[]) => {
const lastIndex = arr.length - 1;
let start = 0;
for (; start <= lastIndex; start++) {
if (arr[start])
break;
}
let end = lastIndex;
for (; end >= 0; end--) {
if (arr[end])
break;
}
if (start === 0 && end === lastIndex)
return arr;
if (start > end)
return [];
return arr.slice(start, end + 1);
}
const resolve = (path: string) => {
let resolvedPath = '',
resolvedAbsolute: boolean;
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path[0] === '/';
// Normalize the path
resolvedPath = normalizeArray(resolvedPath.split('/'),
!resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
const getRelativePath = (from: string, to: string): string => {
from = resolve(from).substr(1);
to = resolve(to).substr(1);
const fromParts = trimArray(from.split('/'));
const toParts = trimArray(to.split('/'));
const length = Math.min(fromParts.length, toParts.length);
let samePartsLength = length;
for (let i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
let outputParts = [];
for (let i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
}
const isAbsolutePath = (path: string): boolean => {
return path.charAt(0) === '/';
}
const getDirname = (path: string): string => {
return path.substring(0, path.lastIndexOf("/"));
}
const getRootDirname = (path: string): string => {
return path.substring(0, path.indexOf("/"));
}
export {
getRelativePath,
isAbsolutePath,
getDirname,
getRootDirname
}