This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathpathUtilities.ts
More file actions
395 lines (339 loc) · 9.75 KB
/
pathUtilities.ts
File metadata and controls
395 lines (339 loc) · 9.75 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Path from 'path';
import * as FS from 'fs';
import * as CP from 'child_process';
const glob = require('glob');
const minimatch = require('minimatch');
/**
* The input paths must use the path syntax of the underlying operating system.
*/
export function makePathAbsolute(absPath: string, relPath: string): string {
return Path.resolve(Path.dirname(absPath), relPath);
}
/**
* Return the relative path between 'path' and 'target'.
* The input paths must use the path syntax of the underlying operating system.
*/
export function makeRelative(target: string, path: string): string {
const t = target.split(Path.sep);
const p = path.split(Path.sep);
let i = 0;
for (; i < Math.min(t.length, p.length) && t[i] === p[i]; i++) {
}
let result = '';
for (; i < p.length; i++) {
result = Path.join(result, p[i]);
}
return result;
}
/**
* Returns a path with a lower case drive letter.
*/
export function normalizeDriveLetter(path: string): string {
const regex = /^([A-Z])(\:[\\\/].*)$/;
if (regex.test(path)) {
path = path.replace(regex, (s, s1, s2) => s1.toLowerCase() + s2);
}
return path;
}
/**
* Change back slashes to forward slashes;
* on Windows and macOS convert to lower case.
*/
export function pathNormalize(path: string) : string {
path = path.replace(/\\/g, '/');
if (process.platform === 'win32' || process.platform === 'darwin') {
path = path.toLowerCase();
}
return path;
}
/**
* On Windows change forward slashes to back slashes
*/
export function pathToNative(path: string): string {
if (process.platform === 'win32') {
path = path.replace(/\//g, '\\');
}
return path;
}
export function pathCompare(path1: string, path2: string): boolean {
return normalizeDriveLetter(path1) === normalizeDriveLetter(path2);
}
/**
* Given an absolute, normalized, and existing file path 'realPath' returns the exact path that the file has on disk.
* On a case insensitive file system, the returned path might differ from the original path by character casing.
* On a case sensitive file system, the returned path will always be identical to the original path.
* In case of errors, null is returned. But you cannot use this function to verify that a path exists.
* realPath does not handle '..' or '.' path segments and it does not take the locale into account.
* Since a drive letter of a Windows path cannot be looked up, realPath normalizes the drive letter to lower case.
*/
export function realPath(path: string): string | null {
let dir = Path.dirname(path);
if (path === dir) { // end recursion
// is this an upper case drive letter?
if (/^[A-Z]\:\\$/.test(path)) {
path = path.toLowerCase();
}
return path;
}
let name = Path.basename(path).toLowerCase();
try {
let entries = FS.readdirSync(dir);
let found = entries.filter(e => e.toLowerCase() === name); // use a case insensitive search
if (found.length === 1) {
// on a case sensitive filesystem we cannot determine here, whether the file exists or not, hence we need the 'file exists' precondition
let prefix = realPath(dir); // recurse
if (prefix) {
return Path.join(prefix, found[0]);
}
} else if (found.length > 1) {
// must be a case sensitive $filesystem
const ix = found.indexOf(name);
if (ix >= 0) { // case sensitive
let prefix = realPath(dir); // recurse
if (prefix) {
return Path.join(prefix, found[ix]);
}
}
}
}
catch (error) {
// silently ignore error
}
return null;
}
/**
* Make sure that all directories of the given path exist (like mkdir -p).
*/
export function mkdirs(path: string) {
if (!FS.existsSync(path)) {
mkdirs(Path.dirname(path));
FS.mkdirSync(path);
}
}
/*
* Lookup the given program on the PATH and return its absolute path on success and undefined otherwise.
*/
export function findOnPath(program: string, args_env: any): string | undefined {
const env = extendObject(extendObject({}, process.env), args_env);
let locator: string;
if (process.platform === 'win32') {
const windir = env['WINDIR'] || 'C:\\Windows';
locator = Path.join(windir, 'System32', 'where.exe');
} else {
locator = '/usr/bin/which';
}
try {
if (FS.existsSync(locator)) {
const lines = CP.execSync(`${locator} ${program}`, { env: env } ).toString().split(/\r?\n/);
if (process.platform === 'win32') {
// return the first path that has a executable extension
const executableExtensions = env['PATHEXT'].toUpperCase();
for (const path of lines) {
const ext = Path.extname(path).toUpperCase();
if (ext && executableExtensions.indexOf(ext + ';') > 0) {
return path;
}
}
} else {
// return the first path
if (lines.length > 0) {
return lines[0];
}
}
return undefined;
} else {
// do not report failure if 'locator' app doesn't exist
}
return program;
}
catch (err) {
// fall through
}
// fail
return undefined;
}
/*
*
*/
export function findExecutable(program: string, args_env: any): string | undefined {
const env = extendObject(extendObject({}, process.env), args_env);
if (process.platform === 'win32' && !Path.extname(program)) {
const PATHEXT = env['PATHEXT'];
if (PATHEXT) {
const executableExtensions = PATHEXT.split(';');
for (const extension of executableExtensions) {
const path = program + extension;
if (FS.existsSync(path)) {
return path;
}
}
}
}
if (FS.existsSync(program)) {
return program;
}
return undefined;
}
//---- the following functions work with Windows and Unix-style paths independent from the underlying OS.
/**
* Returns true if the Windows or Unix-style path is absolute.
*/
export function isAbsolutePath(path: string | null): boolean {
if (path) {
if (path.charAt(0) === '/') {
return true;
}
if (/^[a-zA-Z]\:[\\\/]/.test(path)) {
return true;
}
}
return false;
}
/**
* Convert the given Windows or Unix-style path into a normalized path that only uses forward slashes and has all superflous '..' sequences removed.
* If the path starts with a Windows-style drive letter, a '/' is prepended.
*/
export function normalize(path: string) : string {
path = path.replace(/\\/g, '/');
if (/^[a-zA-Z]\:\//.test(path)) {
path = '/' + path;
}
path = Path.normalize(path); // use node's normalize to remove '<dir>/..' etc.
path = path.replace(/\\/g, '/');
return path;
}
/**
* Convert the given normalized path into a Windows-style path.
*/
export function toWindows(path: string) : string {
if (/^\/[a-zA-Z]\:\//.test(path)) {
path = path.substr(1);
}
path = path.replace(/\//g, '\\');
return path;
}
/**
* Append the given relative path to the absolute path and normalize the result.
*/
export function join(absPath: string, relPath: string) : string {
absPath = normalize(absPath);
relPath = normalize(relPath);
if (absPath.charAt(absPath.length-1) === '/') {
absPath = absPath + relPath;
} else {
absPath = absPath + '/' + relPath;
}
absPath = Path.normalize(absPath);
absPath = absPath.replace(/\\/g, '/');
return absPath;
}
/**
* Return the relative path between 'from' and 'to'.
*/
export function makeRelative2(from: string, to: string): string {
from = normalize(from);
to = normalize(to);
const froms = from.substr(1).split('/');
const tos = to.substr(1).split('/');
while (froms.length > 0 && tos.length > 0 && froms[0] === tos[0]) {
froms.shift();
tos.shift();
}
let l = froms.length - tos.length;
if (l === 0) {
l = tos.length - 1;
}
while (l > 0) {
tos.unshift('..');
l--;
}
return tos.join('/');
}
//---- globbing support -------------------------------------------------
interface IGlobTask {
pattern: string;
opts: any;
}
export function multiGlob(patterns: string[], opts?): Promise<string[]> {
const globTasks = new Array<IGlobTask>();
opts = extendObject({
cache: Object.create(null),
statCache: Object.create(null),
realpathCache: Object.create(null),
symlinks: Object.create(null),
ignore: []
}, opts);
const isExclude = pattern => pattern[0] === '!';
try {
patterns.forEach( (pattern, i) => {
if (isExclude(pattern)) {
return;
}
const ignore = patterns.slice(i).filter(isExclude).map(pattern => pattern.slice(1));
globTasks.push({
pattern: pattern,
opts: extendObject(extendObject({}, opts), {
ignore: opts.ignore.concat(ignore)
})
});
});
} catch (err) {
return Promise.reject(err);
}
return Promise.all(globTasks.map(task => {
return new Promise<string[]>((c, e) => {
glob(task.pattern, task.opts, (err, files: string[]) => {
if (err) {
e(err);
} else {
c(files);
}
});
});
})).then(results => {
const set = new Set<string>();
for (let paths of results) {
for (let p of paths) {
set.add(p);
}
}
let array = new Array<string>();
set.forEach(v => array.push(Path.posix.normalize(v)));
return array;
});
}
export function multiGlobMatches(patterns: string[], path: string): boolean {
let matched = false;
for (const p of patterns) {
const isExclude = p[0] === '!';
if (matched !== isExclude) {
break;
}
matched = minimatch(path, p);
}
return matched;
}
//---- misc
/**
* Copy attributes from fromObject to toObject.
*/
export function extendObject<T extends object> (toObject: T, fromObject: T | undefined): T {
if (fromObject) {
for (let key in fromObject) {
if (fromObject.hasOwnProperty(key)) {
toObject[key] = fromObject[key];
}
}
}
return toObject;
}
export function stripBOM(s: string) : string{
if (s && s[0] === '\uFEFF') {
s = s.substr(1);
}
return s;
}