-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathpath.ts
321 lines (262 loc) · 7.59 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BaseException } from '../exception';
import { TemplateTag } from '../utils/literals';
export class InvalidPathException extends BaseException {
constructor(path: string) { super(`Path ${JSON.stringify(path)} is invalid.`); }
}
export class PathMustBeAbsoluteException extends BaseException {
constructor(path: string) { super(`Path ${JSON.stringify(path)} must be absolute.`); }
}
export class PathCannotBeFragmentException extends BaseException {
constructor(path: string) { super(`Path ${JSON.stringify(path)} cannot be made a fragment.`); }
}
/**
* A Path recognized by most methods in the DevKit.
*/
export type Path = string & {
__PRIVATE_DEVKIT_PATH: void;
};
/**
* A Path fragment (file or directory name) recognized by most methods in the DevKit.
*/
export type PathFragment = Path & {
__PRIVATE_DEVKIT_PATH_FRAGMENT: void;
};
/**
* The Separator for normalized path.
* @type {Path}
*/
export const NormalizedSep = '/' as Path;
/**
* The root of a normalized path.
* @type {Path}
*/
export const NormalizedRoot = NormalizedSep as Path;
/**
* Split a path into multiple path fragments. Each fragments except the last one will end with
* a path separator.
* @param {Path} path The path to split.
* @returns {Path[]} An array of path fragments.
*/
export function split(path: Path): PathFragment[] {
const fragments = path.split(NormalizedSep).map(x => fragment(x));
if (fragments[fragments.length - 1].length === 0) {
fragments.pop();
}
return fragments;
}
/**
*
*/
export function extname(path: Path): string {
const base = basename(path);
const i = base.lastIndexOf('.');
if (i < 1) {
return '';
} else {
return base.substr(i);
}
}
/**
* Return the basename of the path, as a Path. See path.basename
*/
export function basename(path: Path): PathFragment {
const i = path.lastIndexOf(NormalizedSep);
if (i == -1) {
return fragment(path);
} else {
return fragment(path.substr(path.lastIndexOf(NormalizedSep) + 1));
}
}
/**
* Return the dirname of the path, as a Path. See path.dirname
*/
export function dirname(path: Path): Path {
const index = path.lastIndexOf(NormalizedSep);
if (index === -1) {
return '' as Path;
}
const endIndex = index === 0 ? 1 : index; // case of file under root: '/file'
return normalize(path.substr(0, endIndex));
}
/**
* Join multiple paths together, and normalize the result. Accepts strings that will be
* normalized as well (but the original must be a path).
*/
export function join(p1: Path, ...others: string[]): Path {
if (others.length > 0) {
return normalize((p1 ? p1 + NormalizedSep : '') + others.join(NormalizedSep));
} else {
return p1;
}
}
/**
* Returns true if a path is absolute.
*/
export function isAbsolute(p: Path) {
return p.startsWith(NormalizedSep);
}
/**
* Returns a path such that `join(from, relative(from, to)) == to`.
* Both paths must be absolute, otherwise it does not make much sense.
*/
export function relative(from: Path, to: Path): Path {
if (!isAbsolute(from)) {
throw new PathMustBeAbsoluteException(from);
}
if (!isAbsolute(to)) {
throw new PathMustBeAbsoluteException(to);
}
let p: string;
if (from == to) {
p = '';
} else {
const splitFrom = from.split(NormalizedSep);
const splitTo = to.split(NormalizedSep);
while (splitFrom.length > 0 && splitTo.length > 0 && splitFrom[0] == splitTo[0]) {
splitFrom.shift();
splitTo.shift();
}
if (splitFrom.length == 0) {
p = splitTo.join(NormalizedSep);
} else {
p = splitFrom.map(_ => '..').concat(splitTo).join(NormalizedSep);
}
}
return normalize(p);
}
/**
* Returns a Path that is the resolution of p2, from p1. If p2 is absolute, it will return p2,
* otherwise will join both p1 and p2.
*/
export function resolve(p1: Path, p2: Path) {
if (isAbsolute(p2)) {
return p2;
} else {
return join(p1, p2);
}
}
export function fragment(path: string): PathFragment {
if (path.indexOf(NormalizedSep) != -1) {
throw new PathCannotBeFragmentException(path);
}
return path as PathFragment;
}
/**
* normalize() cache to reduce computation. For now this grows and we never flush it, but in the
* future we might want to add a few cache flush to prevent this from growing too large.
*/
let normalizedCache = new Map<string, Path>();
/**
* Reset the cache. This is only useful for testing.
* @private
*/
export function resetNormalizeCache() {
normalizedCache = new Map<string, Path>();
}
/**
* Normalize a string into a Path. This is the only mean to get a Path type from a string that
* represents a system path. This method cache the results as real world paths tend to be
* duplicated often.
* Normalization includes:
* - Windows backslashes `\\` are replaced with `/`.
* - Windows drivers are replaced with `/X/`, where X is the drive letter.
* - Absolute paths starts with `/`.
* - Multiple `/` are replaced by a single one.
* - Path segments `.` are removed.
* - Path segments `..` are resolved.
* - If a path is absolute, having a `..` at the start is invalid (and will throw).
* @param path The path to be normalized.
*/
export function normalize(path: string): Path {
let maybePath = normalizedCache.get(path);
if (!maybePath) {
maybePath = noCacheNormalize(path);
normalizedCache.set(path, maybePath);
}
return maybePath;
}
/**
* The no cache version of the normalize() function. Used for benchmarking and testing.
*/
export function noCacheNormalize(path: string): Path {
if (path == '' || path == '.') {
return '' as Path;
} else if (path == NormalizedRoot) {
return NormalizedRoot;
}
// Match absolute windows path.
const original = path;
if (path.match(/^[A-Z]:[\/\\]/i)) {
path = '\\' + path[0] + '\\' + path.substr(3);
}
// We convert Windows paths as well here.
const p = path.split(/[\/\\]/g);
let relative = false;
let i = 1;
// Special case the first one.
if (p[0] != '') {
p.unshift('.');
relative = true;
}
while (i < p.length) {
if (p[i] == '.') {
p.splice(i, 1);
} else if (p[i] == '..') {
if (i < 2 && !relative) {
throw new InvalidPathException(original);
} else if (i >= 2 && p[i - 1] != '..') {
p.splice(i - 1, 2);
i--;
} else {
i++;
}
} else if (p[i] == '') {
p.splice(i, 1);
} else {
i++;
}
}
if (p.length == 1) {
return p[0] == '' ? NormalizedSep : '' as Path;
} else {
if (p[0] == '.') {
p.shift();
}
return p.join(NormalizedSep) as Path;
}
}
export const path: TemplateTag<Path> = (strings, ...values) => {
return normalize(String.raw(strings, ...values));
};
// Platform-specific paths.
export type WindowsPath = string & {
__PRIVATE_DEVKIT_WINDOWS_PATH: void;
};
export type PosixPath = string & {
__PRIVATE_DEVKIT_POSIX_PATH: void;
};
export function asWindowsPath(path: Path): WindowsPath {
const drive = path.match(/^\/(\w)(?:\/(.*))?$/);
if (drive) {
const subPath = drive[2] ? drive[2].replace(/\//g, '\\') : '';
return `${drive[1]}:\\${subPath}` as WindowsPath;
}
return path.replace(/\//g, '\\') as WindowsPath;
}
export function asPosixPath(path: Path): PosixPath {
return path as string as PosixPath;
}
export function getSystemPath(path: Path): string {
if (process.platform.startsWith('win32')) {
return asWindowsPath(path);
} else {
return asPosixPath(path);
}
}