-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Expand file tree
/
Copy pathpaths.test.ts
More file actions
588 lines (507 loc) · 19.8 KB
/
Copy pathpaths.test.ts
File metadata and controls
588 lines (507 loc) · 19.8 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import {
escapePath,
unescapePath,
isSubpath,
shortenPath,
normalizePath,
resolveToRealPath,
} from './paths.js';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof fs>();
return {
...(actual as object),
realpathSync: (p: string) => p,
};
});
const mockPlatform = (platform: string) => {
vi.stubGlobal(
'process',
Object.create(process, {
platform: {
get: () => platform,
},
}),
);
};
describe('escapePath', () => {
afterEach(() => vi.unstubAllGlobals());
describe('in posix', () => {
beforeEach(() => mockPlatform('linux'));
it.each([
['spaces', 'my file.txt', 'my\\ file.txt'],
['tabs', 'file\twith\ttabs.txt', 'file\\\twith\\\ttabs.txt'],
['parentheses', 'file(1).txt', 'file\\(1\\).txt'],
['square brackets', 'file[backup].txt', 'file\\[backup\\].txt'],
['curly braces', 'file{temp}.txt', 'file\\{temp\\}.txt'],
['semicolons', 'file;name.txt', 'file\\;name.txt'],
['ampersands', 'file&name.txt', 'file\\&name.txt'],
['pipes', 'file|name.txt', 'file\\|name.txt'],
['asterisks', 'file*.txt', 'file\\*.txt'],
['question marks', 'file?.txt', 'file\\?.txt'],
['dollar signs', 'file$name.txt', 'file\\$name.txt'],
['backticks', 'file`name.txt', 'file\\`name.txt'],
['single quotes', "file'name.txt", "file\\'name.txt"],
['double quotes', 'file"name.txt', 'file\\"name.txt'],
['hash symbols', 'file#name.txt', 'file\\#name.txt'],
['exclamation marks', 'file!name.txt', 'file\\!name.txt'],
['tildes', 'file~name.txt', 'file\\~name.txt'],
[
'less than and greater than signs',
'file<name>.txt',
'file\\<name\\>.txt',
],
[
'multiple special characters',
'my file (backup) [v1.2].txt',
'my\\ file\\ \\(backup\\)\\ \\[v1.2\\].txt',
],
['normal file', 'normalfile.txt', 'normalfile.txt'],
['normal path', 'path/to/normalfile.txt', 'path/to/normalfile.txt'],
[
'real world example 1',
'My Documents/Project (2024)/file [backup].txt',
'My\\ Documents/Project\\ \\(2024\\)/file\\ \\[backup\\].txt',
],
[
'real world example 2',
'file with $special &chars!.txt',
'file\\ with\\ \\$special\\ \\&chars\\!.txt',
],
['empty string', '', ''],
[
'all special chars',
' ()[]{};&|*?$`\'"#!<>',
'\\ \\(\\)\\[\\]\\{\\}\\;\\&\\|\\*\\?\\$\\`\\\'\\"\\#\\!\\<\\>',
],
])('should escape %s', (_, input, expected) => {
expect(escapePath(input)).toBe(expected);
});
});
describe('in windows', () => {
beforeEach(() => mockPlatform('win32'));
it.each([
[
'spaces',
'C:\\path with spaces\\file.txt',
'"C:\\path with spaces\\file.txt"',
],
['parentheses', 'file(1).txt', '"file(1).txt"'],
['special chars', 'file&name.txt', '"file&name.txt"'],
['caret', 'file^name.txt', '"file^name.txt"'],
['normal path', 'C:\\path\\to\\file.txt', 'C:\\path\\to\\file.txt'],
])('should escape %s', (_, input, expected) => {
expect(escapePath(input)).toBe(expected);
});
});
});
describe('unescapePath', () => {
afterEach(() => vi.unstubAllGlobals());
describe('in posix', () => {
beforeEach(() => mockPlatform('linux'));
it.each([
['spaces', 'my\\ file.txt', 'my file.txt'],
['tabs', 'file\\\twith\\\ttabs.txt', 'file\twith\ttabs.txt'],
['parentheses', 'file\\(1\\).txt', 'file(1).txt'],
['square brackets', 'file\\[backup\\].txt', 'file[backup].txt'],
['curly braces', 'file\\{temp\\}.txt', 'file{temp}.txt'],
[
'multiple special characters',
'my\\ file\\ \\(backup\\)\\ \\[v1.2\\].txt',
'my file (backup) [v1.2].txt',
],
['normal file', 'normalfile.txt', 'normalfile.txt'],
['normal path', 'path/to/normalfile.txt', 'path/to/normalfile.txt'],
['empty string', '', ''],
])('should unescape %s', (_, input, expected) => {
expect(unescapePath(input)).toBe(expected);
});
it.each([
'my file.txt',
'file(1).txt',
'file[backup].txt',
'My Documents/Project (2024)/file [backup].txt',
'file with $special &chars!.txt',
' ()[]{};&|*?$`\'"#!~<>',
'file\twith\ttabs.txt',
])('should unescape escaped %s', (input) => {
expect(unescapePath(escapePath(input))).toBe(input);
});
});
describe('in windows', () => {
beforeEach(() => mockPlatform('win32'));
it.each([
[
'quoted path',
'"C:\\path with spaces\\file.txt"',
'C:\\path with spaces\\file.txt',
],
['unquoted path', 'C:\\path\\to\\file.txt', 'C:\\path\\to\\file.txt'],
['partially quoted', '"C:\\path', '"C:\\path'],
['empty string', '', ''],
])('should unescape %s', (_, input, expected) => {
expect(unescapePath(input)).toBe(expected);
});
it.each([
'C:\\path\\to\\file.txt',
'C:\\path with spaces\\file.txt',
'file(1).txt',
'file&name.txt',
])('should unescape escaped %s', (input) => {
expect(unescapePath(escapePath(input))).toBe(input);
});
});
});
describe('isSubpath', () => {
it('should return true for a direct subpath', () => {
expect(isSubpath('/a/b', '/a/b/c')).toBe(true);
});
it('should return true for the same path', () => {
expect(isSubpath('/a/b', '/a/b')).toBe(true);
});
it('should return false for a parent path', () => {
expect(isSubpath('/a/b/c', '/a/b')).toBe(false);
});
it('should return false for a completely different path', () => {
expect(isSubpath('/a/b', '/x/y')).toBe(false);
});
it('should handle relative paths', () => {
expect(isSubpath('a/b', 'a/b/c')).toBe(true);
expect(isSubpath('a/b', 'a/c')).toBe(false);
});
it('should handle paths with ..', () => {
expect(isSubpath('/a/b', '/a/b/../b/c')).toBe(true);
expect(isSubpath('/a/b', '/a/c/../b')).toBe(true);
});
it('should handle root paths', () => {
expect(isSubpath('/', '/a')).toBe(true);
expect(isSubpath('/a', '/')).toBe(false);
});
it('should handle trailing slashes', () => {
expect(isSubpath('/a/b/', '/a/b/c')).toBe(true);
expect(isSubpath('/a/b', '/a/b/c/')).toBe(true);
expect(isSubpath('/a/b/', '/a/b/c/')).toBe(true);
});
});
describe('isSubpath on Windows', () => {
afterEach(() => vi.unstubAllGlobals());
beforeEach(() => mockPlatform('win32'));
it('should return true for a direct subpath on Windows', () => {
expect(isSubpath('C:\\Users\\Test', 'C:\\Users\\Test\\file.txt')).toBe(
true,
);
});
it('should return true for the same path on Windows', () => {
expect(isSubpath('C:\\Users\\Test', 'C:\\Users\\Test')).toBe(true);
});
it('should return false for a parent path on Windows', () => {
expect(isSubpath('C:\\Users\\Test\\file.txt', 'C:\\Users\\Test')).toBe(
false,
);
});
it('should return false for a different drive on Windows', () => {
expect(isSubpath('C:\\Users\\Test', 'D:\\Users\\Test')).toBe(false);
});
it('should be case-insensitive for drive letters on Windows', () => {
expect(isSubpath('c:\\Users\\Test', 'C:\\Users\\Test\\file.txt')).toBe(
true,
);
});
it('should be case-insensitive for path components on Windows', () => {
expect(isSubpath('C:\\Users\\Test', 'c:\\users\\test\\file.txt')).toBe(
true,
);
});
it('should handle mixed slashes on Windows', () => {
expect(isSubpath('C:/Users/Test', 'C:\\Users\\Test\\file.txt')).toBe(true);
});
it('should handle trailing slashes on Windows', () => {
expect(isSubpath('C:\\Users\\Test\\', 'C:\\Users\\Test\\file.txt')).toBe(
true,
);
});
it('should handle relative paths correctly on Windows', () => {
expect(isSubpath('Users\\Test', 'Users\\Test\\file.txt')).toBe(true);
expect(isSubpath('Users\\Test\\file.txt', 'Users\\Test')).toBe(false);
});
});
describe('shortenPath', () => {
describe.skipIf(process.platform === 'win32')('on POSIX', () => {
it('should not shorten a path that is shorter than maxLen', () => {
const p = '/path/to/file.txt';
expect(shortenPath(p, 40)).toBe(p);
});
it('should not shorten a path that is equal to maxLen', () => {
const p = '/path/to/file.txt';
expect(shortenPath(p, p.length)).toBe(p);
});
it('should shorten a long path, keeping start and end from a short limit', () => {
const p = '/path/to/a/very/long/directory/name/file.txt';
expect(shortenPath(p, 25)).toBe('/path/.../name/file.txt');
});
it('should shorten a long path, keeping more from the end from a longer limit', () => {
const p = '/path/to/a/very/long/directory/name/file.txt';
expect(shortenPath(p, 35)).toBe('/path/.../directory/name/file.txt');
});
it('should handle deep paths where few segments from the end fit', () => {
const p = '/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/file.txt';
expect(shortenPath(p, 20)).toBe('/a/.../y/z/file.txt');
});
it('should handle deep paths where many segments from the end fit', () => {
const p = '/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/file.txt';
expect(shortenPath(p, 45)).toBe(
'/a/.../l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/file.txt',
);
});
it('should handle a long filename in the root when it needs shortening', () => {
const p = '/a-very-long-filename-that-needs-to-be-shortened.txt';
expect(shortenPath(p, 40)).toBe(
'/a-very-long-filen...o-be-shortened.txt',
);
});
it('should handle root path', () => {
const p = '/';
expect(shortenPath(p, 10)).toBe('/');
});
it('should handle a path with one long segment after root', () => {
const p = '/a-very-long-directory-name';
expect(shortenPath(p, 20)).toBe('/a-very-...ory-name');
});
it('should handle a path with just a long filename (no root)', () => {
const p = 'a-very-long-filename-that-needs-to-be-shortened.txt';
expect(shortenPath(p, 40)).toBe(
'a-very-long-filena...o-be-shortened.txt',
);
});
it('should fallback to truncating earlier segments while keeping the last intact', () => {
const p = '/abcdef/fghij.txt';
const result = shortenPath(p, 10);
expect(result).toBe('/fghij.txt');
expect(result.length).toBeLessThanOrEqual(10);
});
it('should fallback by truncating start and middle segments when needed', () => {
const p = '/averylongcomponentname/another/short.txt';
const result = shortenPath(p, 25);
expect(result).toBe('/averylo.../.../short.txt');
expect(result.length).toBeLessThanOrEqual(25);
});
it('should show only the last segment when maxLen is tiny', () => {
const p = '/foo/bar/baz.txt';
const result = shortenPath(p, 8);
expect(result).toBe('/baz.txt');
expect(result.length).toBeLessThanOrEqual(8);
});
it('should fall back to simple truncation when the last segment exceeds maxLen', () => {
const longFile = 'x'.repeat(60) + '.txt';
const p = `/really/long/${longFile}`;
const result = shortenPath(p, 50);
expect(result).toBe('/really/long/xxxxxxxxxx...xxxxxxxxxxxxxxxxxxx.txt');
expect(result.length).toBeLessThanOrEqual(50);
});
it('should handle relative paths without a root', () => {
const p = 'foo/bar/baz/qux.txt';
const result = shortenPath(p, 18);
expect(result).toBe('foo/.../qux.txt');
expect(result.length).toBeLessThanOrEqual(18);
});
it('should ignore empty segments created by repeated separators', () => {
const p = '/foo//bar///baz/verylongname.txt';
const result = shortenPath(p, 20);
expect(result).toBe('.../verylongname.txt');
expect(result.length).toBeLessThanOrEqual(20);
});
});
describe.skipIf(process.platform !== 'win32')('on Windows', () => {
it('should not shorten a path that is shorter than maxLen', () => {
const p = 'C\\Users\\Test\\file.txt';
expect(shortenPath(p, 40)).toBe(p);
});
it('should not shorten a path that is equal to maxLen', () => {
const p = 'C\\path\\to\\file.txt';
expect(shortenPath(p, p.length)).toBe(p);
});
it('should shorten a long path, keeping start and end from a short limit', () => {
const p = 'C\\path\\to\\a\\very\\long\\directory\\name\\file.txt';
expect(shortenPath(p, 30)).toBe('C\\...\\directory\\name\\file.txt');
});
it('should shorten a long path, keeping more from the end from a longer limit', () => {
const p = 'C\\path\\to\\a\\very\\long\\directory\\name\\file.txt';
expect(shortenPath(p, 42)).toBe(
'C\\...\\a\\very\\long\\directory\\name\\file.txt',
);
});
it('should handle deep paths where few segments from the end fit', () => {
const p =
'C\\a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z\\file.txt';
expect(shortenPath(p, 22)).toBe('C\\...\\w\\x\\y\\z\\file.txt');
});
it('should handle deep paths where many segments from the end fit', () => {
const p =
'C\\a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z\\file.txt';
expect(shortenPath(p, 47)).toBe(
'C\\...\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z\\file.txt',
);
});
it('should handle a long filename in the root when it needs shortening', () => {
const p = 'C\\a-very-long-filename-that-needs-to-be-shortened.txt';
expect(shortenPath(p, 40)).toBe(
'C\\a-very-long-file...o-be-shortened.txt',
);
});
it('should handle root path', () => {
const p = 'C\\';
expect(shortenPath(p, 10)).toBe('C\\');
});
it('should handle a path with one long segment after root', () => {
const p = 'C\\a-very-long-directory-name';
expect(shortenPath(p, 22)).toBe('C\\a-very-...tory-name');
});
it('should handle a path with just a long filename (no root)', () => {
const p = 'a-very-long-filename-that-needs-to-be-shortened.txt';
expect(shortenPath(p, 40)).toBe(
'a-very-long-filena...o-be-shortened.txt',
);
});
it('should fallback to truncating earlier segments while keeping the last intact', () => {
const p = 'C\\abcdef\\fghij.txt';
const result = shortenPath(p, 15);
expect(result).toBe('C\\...\\fghij.txt');
expect(result.length).toBeLessThanOrEqual(15);
});
it('should fallback by truncating start and middle segments when needed', () => {
const p = 'C\\averylongcomponentname\\another\\short.txt';
const result = shortenPath(p, 30);
expect(result).toBe('C\\...\\another\\short.txt');
expect(result.length).toBeLessThanOrEqual(30);
});
it('should show only the last segment for tiny maxLen values', () => {
const p = 'C\\foo\\bar\\baz.txt';
const result = shortenPath(p, 12);
expect(result).toBe('...\\baz.txt');
expect(result.length).toBeLessThanOrEqual(12);
});
it('should keep the drive prefix when space allows', () => {
const p = 'C\\foo\\bar\\baz.txt';
const result = shortenPath(p, 14);
expect(result).toBe('C\\...\\baz.txt');
expect(result.length).toBeLessThanOrEqual(14);
});
it('should fall back when the last segment exceeds maxLen on Windows', () => {
const longFile = 'x'.repeat(60) + '.txt';
const p = `C\\really\\long\\${longFile}`;
const result = shortenPath(p, 40);
expect(result).toBe('C\\really\\long\\xxxx...xxxxxxxxxxxxxx.txt');
expect(result.length).toBeLessThanOrEqual(40);
});
it('should handle UNC paths with limited space', () => {
const p = '\\server\\share\\deep\\path\\file.txt';
const result = shortenPath(p, 25);
expect(result).toBe('\\server\\...\\path\\file.txt');
expect(result.length).toBeLessThanOrEqual(25);
});
it('should collapse UNC paths further when maxLen shrinks', () => {
const p = '\\server\\share\\deep\\path\\file.txt';
const result = shortenPath(p, 18);
expect(result).toBe('\\s...\\...\\file.txt');
expect(result.length).toBeLessThanOrEqual(18);
});
});
});
describe('resolveToRealPath', () => {
it.each([
{
description:
'should return path as-is if no special characters or protocol',
input: path.resolve('simple', 'path'),
expected: path.resolve('simple', 'path'),
},
{
description: 'should remove file:// protocol',
input: pathToFileURL(path.resolve('path', 'to', 'file')).toString(),
expected: path.resolve('path', 'to', 'file'),
},
{
description: 'should decode URI components',
input: path.resolve('path', 'to', 'some folder').replace(/ /g, '%20'),
expected: path.resolve('path', 'to', 'some folder'),
},
{
description: 'should handle both file protocol and encoding',
input: pathToFileURL(path.resolve('path', 'to', 'My Project')).toString(),
expected: path.resolve('path', 'to', 'My Project'),
},
])('$description', ({ input, expected }) => {
expect(resolveToRealPath(input)).toBe(expected);
});
it('should return decoded path even if fs.realpathSync fails with ENOENT', () => {
vi.spyOn(fs, 'realpathSync').mockImplementationOnce(() => {
const err = new Error('File not found') as NodeJS.ErrnoException;
err.code = 'ENOENT';
throw err;
});
const p = path.resolve('path', 'to', 'New Project');
const input = pathToFileURL(p).toString();
const expected = p;
expect(resolveToRealPath(input)).toBe(expected);
});
it('should recursively resolve symlinks for non-existent child paths', () => {
const parentPath = path.resolve('/some/parent/path');
const resolvedParentPath = path.resolve('/resolved/parent/path');
const childPath = path.resolve(parentPath, 'child', 'file.txt');
const expectedPath = path.resolve(resolvedParentPath, 'child', 'file.txt');
vi.spyOn(fs, 'realpathSync').mockImplementation((p) => {
const pStr = p.toString();
if (pStr === parentPath) {
return resolvedParentPath;
}
const err = new Error('ENOENT') as NodeJS.ErrnoException;
err.code = 'ENOENT';
throw err;
});
expect(resolveToRealPath(childPath)).toBe(expectedPath);
});
});
describe('normalizePath', () => {
it('should resolve a relative path to an absolute path', () => {
const result = normalizePath('some/relative/path');
expect(result).toMatch(/^\/|^[a-z]:\//);
});
it('should convert all backslashes to forward slashes', () => {
const result = normalizePath(path.resolve('some', 'path'));
expect(result).not.toContain('\\');
});
describe.skipIf(process.platform !== 'win32')('on Windows', () => {
it('should lowercase the entire path', () => {
const result = normalizePath('C:\\Users\\TEST');
expect(result).toBe(result.toLowerCase());
});
it('should normalize drive letters to lowercase', () => {
const result = normalizePath('C:\\');
expect(result).toMatch(/^c:\//);
});
it('should handle mixed separators', () => {
const result = normalizePath('C:/Users\\Test/file.txt');
expect(result).not.toContain('\\');
expect(result).toMatch(/^c:\/users\/test\/file\.txt$/);
});
});
describe.skipIf(process.platform === 'win32')('on POSIX', () => {
it('should preserve case', () => {
const result = normalizePath('/usr/Local/Bin');
expect(result).toContain('Local');
expect(result).toContain('Bin');
});
it('should use forward slashes', () => {
const result = normalizePath('/usr/local/bin');
expect(result).toBe('/usr/local/bin');
});
});
});