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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { isEqual } from 'vs/base/common/extpath';
import { posix } from 'vs/base/common/path';
import { ResourceMap } from 'vs/base/common/map';
import { IFileStat, IFileService, FileSystemProviderCapabilities } from 'vs/platform/files/common/files';
import { rtrim, startsWithIgnoreCase, equalsIgnoreCase } from 'vs/base/common/strings';
import { coalesce } from 'vs/base/common/arrays';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { memoize } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { joinPath, isEqualOrParent, basenameOrAuthority } from 'vs/base/common/resources';
import { IFilesConfiguration, SortOrder } from 'vs/workbench/contrib/files/common/files';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { ExplorerFileNestingTrie } from 'vs/workbench/contrib/files/common/explorerFileNestingTrie';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { assertIsDefined } from 'vs/base/common/types';
export class ExplorerModel implements IDisposable {
private _roots!: ExplorerItem[];
private _listener: IDisposable;
private readonly _onDidChangeRoots = new Emitter<void>();
constructor(
private readonly contextService: IWorkspaceContextService,
private readonly uriIdentityService: IUriIdentityService,
fileService: IFileService,
configService: IConfigurationService,
) {
const setRoots = () => this._roots = this.contextService.getWorkspace().folders
.map(folder => new ExplorerItem(folder.uri, fileService, configService, undefined, true, false, false, folder.name));
setRoots();
this._listener = this.contextService.onDidChangeWorkspaceFolders(() => {
setRoots();
this._onDidChangeRoots.fire();
});
}
get roots(): ExplorerItem[] {
return this._roots;
}
get onDidChangeRoots(): Event<void> {
return this._onDidChangeRoots.event;
}
/**
* Returns an array of child stat from this stat that matches with the provided path.
* Starts matching from the first root.
* Will return empty array in case the FileStat does not exist.
*/
findAll(resource: URI): ExplorerItem[] {
return coalesce(this.roots.map(root => root.find(resource)));
}
/**
* Returns a FileStat that matches the passed resource.
* In case multiple FileStat are matching the resource (same folder opened multiple times) returns the FileStat that has the closest root.
* Will return undefined in case the FileStat does not exist.
*/
findClosest(resource: URI): ExplorerItem | null {
const folder = this.contextService.getWorkspaceFolder(resource);
if (folder) {
const root = this.roots.find(r => this.uriIdentityService.extUri.isEqual(r.resource, folder.uri));
if (root) {
return root.find(resource);
}
}
return null;
}
dispose(): void {
dispose(this._listener);
}
}
export class ExplorerItem {
protected _isDirectoryResolved: boolean;
public isError = false;
private _isExcluded = false;
public nestedParent: ExplorerItem | undefined;
public nestedChildren: ExplorerItem[] | undefined;
constructor(
public resource: URI,
private readonly fileService: IFileService,
private readonly configService: IConfigurationService,
private _parent: ExplorerItem | undefined,
private _isDirectory?: boolean,
private _isSymbolicLink?: boolean,
private _readonly?: boolean,
private _name: string = basenameOrAuthority(resource),
private _mtime?: number,
private _unknown = false
) {
this._isDirectoryResolved = false;
}
get isExcluded(): boolean {
if (this._isExcluded) {
return true;
}
if (!this._parent) {
return false;
}
return this._parent.isExcluded;
}
set isExcluded(value: boolean) {
this._isExcluded = value;
}
hasChildren(filter: (stat: ExplorerItem) => boolean): boolean {
if (this.hasNests) {
return this.nestedChildren?.some(c => filter(c)) ?? false;
} else {
return this.isDirectory;
}
}
get hasNests() {
return !!(this.nestedChildren?.length);
}
get isDirectoryResolved(): boolean {
return this._isDirectoryResolved;
}
get isSymbolicLink(): boolean {
return !!this._isSymbolicLink;
}
get isDirectory(): boolean {
return !!this._isDirectory;
}
get isReadonly(): boolean {
return this._readonly || this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly);
}
get mtime(): number | undefined {
return this._mtime;
}
get name(): string {
return this._name;
}
get isUnknown(): boolean {
return this._unknown;
}
get parent(): ExplorerItem | undefined {
return this._parent;
}
get root(): ExplorerItem {
if (!this._parent) {
return this;
}
return this._parent.root;
}
@memoize get children(): Map<string, ExplorerItem> {
return new Map<string, ExplorerItem>();
}
private updateName(value: string): void {
// Re-add to parent since the parent has a name map to children and the name might have changed
if (this._parent) {
this._parent.removeChild(this);
}
this._name = value;
if (this._parent) {
this._parent.addChild(this);
}
}
getId(): string {
return this.resource.toString();
}
toString(): string {
return `ExplorerItem: ${this.name}`;
}
get isRoot(): boolean {
return this === this.root;
}
static create(fileService: IFileService, configService: IConfigurationService, raw: IFileStat, parent: ExplorerItem | undefined, resolveTo?: readonly URI[]): ExplorerItem {
const stat = new ExplorerItem(raw.resource, fileService, configService, parent, raw.isDirectory, raw.isSymbolicLink, raw.readonly, raw.name, raw.mtime, !raw.isFile && !raw.isDirectory);
// Recursively add children if present
if (stat.isDirectory) {
// isDirectoryResolved is a very important indicator in the stat model that tells if the folder was fully resolved
// the folder is fully resolved if either it has a list of children or the client requested this by using the resolveTo
// array of resource path to resolve.
stat._isDirectoryResolved = !!raw.children || (!!resolveTo && resolveTo.some((r) => {
return isEqualOrParent(r, stat.resource);
}));
// Recurse into children
if (raw.children) {
for (let i = 0, len = raw.children.length; i < len; i++) {
const child = ExplorerItem.create(fileService, configService, raw.children[i], stat, resolveTo);
stat.addChild(child);
}
}
}
return stat;
}
/**
* Merges the stat which was resolved from the disk with the local stat by copying over properties
* and children. The merge will only consider resolved stat elements to avoid overwriting data which
* exists locally.
*/
static mergeLocalWithDisk(disk: ExplorerItem, local: ExplorerItem): void {
if (disk.resource.toString() !== local.resource.toString()) {
return; // Merging only supported for stats with the same resource
}
// Stop merging when a folder is not resolved to avoid loosing local data
const mergingDirectories = disk.isDirectory || local.isDirectory;
if (mergingDirectories && local._isDirectoryResolved && !disk._isDirectoryResolved) {
return;
}
// Properties
local.resource = disk.resource;
if (!local.isRoot) {
local.updateName(disk.name);
}
local._isDirectory = disk.isDirectory;
local._mtime = disk.mtime;
local._isDirectoryResolved = disk._isDirectoryResolved;
local._isSymbolicLink = disk.isSymbolicLink;
local.isError = disk.isError;
// Merge Children if resolved
if (mergingDirectories && disk._isDirectoryResolved) {
// Map resource => stat
const oldLocalChildren = new ResourceMap<ExplorerItem>();
local.children.forEach(child => {
oldLocalChildren.set(child.resource, child);
});
// Clear current children
local.children.clear();
// Merge received children
disk.children.forEach(diskChild => {
const formerLocalChild = oldLocalChildren.get(diskChild.resource);
// Existing child: merge
if (formerLocalChild) {
ExplorerItem.mergeLocalWithDisk(diskChild, formerLocalChild);
local.addChild(formerLocalChild);
oldLocalChildren.delete(diskChild.resource);
}
// New child: add
else {
local.addChild(diskChild);
}
});
oldLocalChildren.forEach(oldChild => {
if (oldChild instanceof NewExplorerItem) {
local.addChild(oldChild);
}
});
}
}
/**
* Adds a child element to this folder.
*/
addChild(child: ExplorerItem): void {
// Inherit some parent properties to child
child._parent = this;
child.updateResource(false);
this.children.set(this.getPlatformAwareName(child.name), child);
}
getChild(name: string): ExplorerItem | undefined {
return this.children.get(this.getPlatformAwareName(name));
}
fetchChildren(sortOrder: SortOrder): ExplorerItem[] | Promise<ExplorerItem[]> {
const nestingConfig = this.configService.getValue<IFilesConfiguration>({ resource: this.root.resource }).explorer.fileNesting;
// fast path when the children can be resolved sync
if (nestingConfig.enabled && this.nestedChildren) {
return this.nestedChildren;
}
return (async () => {
if (!this._isDirectoryResolved) {
// Resolve metadata only when the mtime is needed since this can be expensive
// Mtime is only used when the sort order is 'modified'
const resolveMetadata = sortOrder === SortOrder.Modified;
this.isError = false;
try {
const stat = await this.fileService.resolve(this.resource, { resolveSingleChildDescendants: true, resolveMetadata });
const resolved = ExplorerItem.create(this.fileService, this.configService, stat, this);
ExplorerItem.mergeLocalWithDisk(resolved, this);
} catch (e) {
this.isError = true;
throw e;
}
this._isDirectoryResolved = true;
}
const items: ExplorerItem[] = [];
if (nestingConfig.enabled) {
const fileChildren: [string, ExplorerItem][] = [];
const dirChildren: [string, ExplorerItem][] = [];
for (const child of this.children.entries()) {
child[1].nestedParent = undefined;
if (child[1].isDirectory) {
dirChildren.push(child);
} else {
fileChildren.push(child);
}
}
const nested = this.fileNester.nest(
fileChildren.map(([name]) => name),
this.getPlatformAwareName(this.name));
for (const [fileEntryName, fileEntryItem] of fileChildren) {
const nestedItems = nested.get(fileEntryName);
if (nestedItems !== undefined) {
fileEntryItem.nestedChildren = [];
for (const name of nestedItems.keys()) {
const child = assertIsDefined(this.children.get(name));
fileEntryItem.nestedChildren.push(child);
child.nestedParent = fileEntryItem;
}
items.push(fileEntryItem);
} else {
fileEntryItem.nestedChildren = undefined;
}
}
for (const [_, dirEntryItem] of dirChildren.values()) {
items.push(dirEntryItem);
}
} else {
this.children.forEach(child => {
items.push(child);
});
}
return items;
})();
}
private _fileNester: ExplorerFileNestingTrie | undefined;
private get fileNester(): ExplorerFileNestingTrie {
if (!this.root._fileNester) {
const nestingConfig = this.configService.getValue<IFilesConfiguration>({ resource: this.root.resource }).explorer.fileNesting;
const patterns = Object.entries(nestingConfig.patterns)
.filter(entry =>
typeof (entry[0]) === 'string' && typeof (entry[1]) === 'string' && entry[0] && entry[1])
.map(([parentPattern, childrenPatterns]) =>
[
this.getPlatformAwareName(parentPattern.trim()),
childrenPatterns.split(',').map(p => this.getPlatformAwareName(p.trim().replace(/\u200b/g, '')))
] as [string, string[]]);
this.root._fileNester = new ExplorerFileNestingTrie(patterns);
}
return this.root._fileNester;
}
/**
* Removes a child element from this folder.
*/
removeChild(child: ExplorerItem): void {
this.nestedChildren = undefined;
this.children.delete(this.getPlatformAwareName(child.name));
}
forgetChildren(): void {
this.children.clear();
this.nestedChildren = undefined;
this._isDirectoryResolved = false;
this._fileNester = undefined;
}
private getPlatformAwareName(name: string): string {
return this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.PathCaseSensitive) ? name : name.toLowerCase();
}
/**
* Moves this element under a new parent element.
*/
move(newParent: ExplorerItem): void {
if (this.nestedParent) {
this.nestedParent.removeChild(this);
}
if (this._parent) {
this._parent.removeChild(this);
}
newParent.removeChild(this); // make sure to remove any previous version of the file if any
newParent.addChild(this);
this.updateResource(true);
}
private updateResource(recursive: boolean): void {
if (this._parent) {
this.resource = joinPath(this._parent.resource, this.name);
}
if (recursive) {
if (this.isDirectory) {
this.children.forEach(child => {
child.updateResource(true);
});
}
}
}
/**
* Tells this stat that it was renamed. This requires changes to all children of this stat (if any)
* so that the path property can be updated properly.
*/
rename(renamedStat: { name: string; mtime?: number }): void {
// Merge a subset of Properties that can change on rename
this.updateName(renamedStat.name);
this._mtime = renamedStat.mtime;
// Update Paths including children
this.updateResource(true);
}
/**
* Returns a child stat from this stat that matches with the provided path.
* Will return "null" in case the child does not exist.
*/
find(resource: URI): ExplorerItem | null {
// Return if path found
// For performance reasons try to do the comparison as fast as possible
const ignoreCase = !this.fileService.hasCapability(resource, FileSystemProviderCapabilities.PathCaseSensitive);
if (resource && this.resource.scheme === resource.scheme && equalsIgnoreCase(this.resource.authority, resource.authority) &&
(ignoreCase ? startsWithIgnoreCase(resource.path, this.resource.path) : resource.path.startsWith(this.resource.path))) {
return this.findByPath(rtrim(resource.path, posix.sep), this.resource.path.length, ignoreCase);
}
return null; //Unable to find
}
private findByPath(path: string, index: number, ignoreCase: boolean): ExplorerItem | null {
if (isEqual(rtrim(this.resource.path, posix.sep), path, ignoreCase)) {
return this;
}
if (this.isDirectory) {
// Ignore separtor to more easily deduct the next name to search
while (index < path.length && path[index] === posix.sep) {
index++;
}
let indexOfNextSep = path.indexOf(posix.sep, index);
if (indexOfNextSep === -1) {
// If there is no separator take the remainder of the path
indexOfNextSep = path.length;
}
// The name to search is between two separators
const name = path.substring(index, indexOfNextSep);
const child = this.children.get(this.getPlatformAwareName(name));
if (child) {
// We found a child with the given name, search inside it
return child.findByPath(path, indexOfNextSep, ignoreCase);
}
}
return null;
}
}
export class NewExplorerItem extends ExplorerItem {
constructor(fileService: IFileService, configService: IConfigurationService, parent: ExplorerItem, isDirectory: boolean) {
super(URI.file(''), fileService, configService, parent, isDirectory);
this._isDirectoryResolved = true;
}
}
|