Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/workbench/contrib/files/common/explorerFileNestingTrie.ts
5243 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
type FilenameAttributes = {
7
// index.test in index.test.json
8
basename: string;
9
// json in index.test.json
10
extname: string;
11
// my-folder in my-folder/index.test.json
12
dirname: string;
13
};
14
15
/**
16
* A sort of double-ended trie, used to efficiently query for matches to "star" patterns, where
17
* a given key represents a parent and may contain a capturing group ("*"), which can then be
18
* referenced via the token "$(capture)" in associated child patterns.
19
*
20
* The generated tree will have at most two levels, as subtrees are flattened rather than nested.
21
*
22
* Example:
23
* The config: [
24
* [ *.ts , [ $(capture).*.ts ; $(capture).js ] ]
25
* [ *.js , [ $(capture).min.js ] ] ]
26
* Nests the files: [ a.ts ; a.d.ts ; a.js ; a.min.js ; b.ts ; b.min.js ]
27
* As:
28
* - a.ts => [ a.d.ts ; a.js ; a.min.js ]
29
* - b.ts => [ ]
30
* - b.min.ts => [ ]
31
*/
32
export class ExplorerFileNestingTrie {
33
private root = new PreTrie();
34
35
constructor(config: [string, string[]][]) {
36
for (const [parentPattern, childPatterns] of config) {
37
for (const childPattern of childPatterns) {
38
this.root.add(parentPattern, childPattern);
39
}
40
}
41
}
42
43
toString() {
44
return this.root.toString();
45
}
46
47
private getAttributes(filename: string, dirname: string): FilenameAttributes {
48
const lastDot = filename.lastIndexOf('.');
49
if (lastDot < 1) {
50
return {
51
dirname,
52
basename: filename,
53
extname: ''
54
};
55
} else {
56
return {
57
dirname,
58
basename: filename.substring(0, lastDot),
59
extname: filename.substring(lastDot + 1)
60
};
61
}
62
}
63
64
nest(files: string[], dirname: string): Map<string, Set<string>> {
65
const parentFinder = new PreTrie();
66
67
for (const potentialParent of files) {
68
const attributes = this.getAttributes(potentialParent, dirname);
69
const children = this.root.get(potentialParent, attributes);
70
for (const child of children) {
71
parentFinder.add(child, potentialParent);
72
}
73
}
74
75
const findAllRootAncestors = (file: string, seen: Set<string> = new Set()): string[] => {
76
if (seen.has(file)) { return []; }
77
seen.add(file);
78
const attributes = this.getAttributes(file, dirname);
79
const ancestors = parentFinder.get(file, attributes);
80
if (ancestors.length === 0) {
81
return [file];
82
}
83
84
if (ancestors.length === 1 && ancestors[0] === file) {
85
return [file];
86
}
87
88
return ancestors.flatMap(a => findAllRootAncestors(a, seen));
89
};
90
91
const result = new Map<string, Set<string>>();
92
for (const file of files) {
93
let ancestors = findAllRootAncestors(file);
94
if (ancestors.length === 0) { ancestors = [file]; }
95
for (const ancestor of ancestors) {
96
let existing = result.get(ancestor);
97
if (!existing) { result.set(ancestor, existing = new Set()); }
98
if (file !== ancestor) {
99
existing.add(file);
100
}
101
}
102
}
103
return result;
104
}
105
}
106
107
/** Export for test only. */
108
export class PreTrie {
109
private value: SufTrie = new SufTrie();
110
111
private map: Map<string, PreTrie> = new Map();
112
113
add(key: string, value: string) {
114
if (key === '') {
115
this.value.add(key, value);
116
} else if (key[0] === '*') {
117
this.value.add(key, value);
118
} else {
119
const head = key[0];
120
const rest = key.slice(1);
121
let existing = this.map.get(head);
122
if (!existing) {
123
this.map.set(head, existing = new PreTrie());
124
}
125
existing.add(rest, value);
126
}
127
}
128
129
get(key: string, attributes: FilenameAttributes): string[] {
130
const results: string[] = [];
131
results.push(...this.value.get(key, attributes));
132
133
const head = key[0];
134
const rest = key.slice(1);
135
const existing = this.map.get(head);
136
if (existing) {
137
results.push(...existing.get(rest, attributes));
138
}
139
140
return results;
141
}
142
143
toString(indentation = ''): string {
144
const lines = [];
145
if (this.value.hasItems) {
146
lines.push('* => \n' + this.value.toString(indentation + ' '));
147
}
148
[...this.map.entries()].map(([key, trie]) =>
149
lines.push('^' + key + ' => \n' + trie.toString(indentation + ' ')));
150
return lines.map(l => indentation + l).join('\n');
151
}
152
}
153
154
/** Export for test only. */
155
export class SufTrie {
156
private star: SubstitutionString[] = [];
157
private epsilon: SubstitutionString[] = [];
158
159
private map: Map<string, SufTrie> = new Map();
160
hasItems: boolean = false;
161
162
add(key: string, value: string) {
163
this.hasItems = true;
164
if (key === '*') {
165
this.star.push(new SubstitutionString(value));
166
} else if (key === '') {
167
this.epsilon.push(new SubstitutionString(value));
168
} else {
169
const tail = key[key.length - 1];
170
const rest = key.slice(0, key.length - 1);
171
if (tail === '*') {
172
throw Error('Unexpected star in SufTrie key: ' + key);
173
} else {
174
let existing = this.map.get(tail);
175
if (!existing) {
176
this.map.set(tail, existing = new SufTrie());
177
}
178
existing.add(rest, value);
179
}
180
}
181
}
182
183
get(key: string, attributes: FilenameAttributes): string[] {
184
const results: string[] = [];
185
if (key === '') {
186
results.push(...this.epsilon.map(ss => ss.substitute(attributes)));
187
}
188
if (this.star.length) {
189
results.push(...this.star.map(ss => ss.substitute(attributes, key)));
190
}
191
192
const tail = key[key.length - 1];
193
const rest = key.slice(0, key.length - 1);
194
const existing = this.map.get(tail);
195
if (existing) {
196
results.push(...existing.get(rest, attributes));
197
}
198
199
return results;
200
}
201
202
toString(indentation = ''): string {
203
const lines = [];
204
if (this.star.length) {
205
lines.push('* => ' + this.star.join('; '));
206
}
207
208
if (this.epsilon.length) {
209
// allow-any-unicode-next-line
210
lines.push('ε => ' + this.epsilon.join('; '));
211
}
212
213
[...this.map.entries()].map(([key, trie]) =>
214
lines.push(key + '$' + ' => \n' + trie.toString(indentation + ' ')));
215
216
return lines.map(l => indentation + l).join('\n');
217
}
218
}
219
220
const enum SubstitutionType {
221
capture = 'capture',
222
basename = 'basename',
223
dirname = 'dirname',
224
extname = 'extname',
225
}
226
227
const substitutionStringTokenizer = /\$[({](capture|basename|dirname|extname)[)}]/g;
228
229
class SubstitutionString {
230
231
private tokens: (string | { capture: SubstitutionType })[] = [];
232
233
constructor(pattern: string) {
234
substitutionStringTokenizer.lastIndex = 0;
235
let token;
236
let lastIndex = 0;
237
while (token = substitutionStringTokenizer.exec(pattern)) {
238
const prefix = pattern.slice(lastIndex, token.index);
239
this.tokens.push(prefix);
240
241
const type = token[1];
242
switch (type) {
243
case SubstitutionType.basename:
244
case SubstitutionType.dirname:
245
case SubstitutionType.extname:
246
case SubstitutionType.capture:
247
this.tokens.push({ capture: type });
248
break;
249
default: throw Error('unknown substitution type: ' + type);
250
}
251
lastIndex = token.index + token[0].length;
252
}
253
254
if (lastIndex !== pattern.length) {
255
const suffix = pattern.slice(lastIndex, pattern.length);
256
this.tokens.push(suffix);
257
}
258
}
259
260
substitute(attributes: FilenameAttributes, capture?: string): string {
261
return this.tokens.map(t => {
262
if (typeof t === 'string') { return t; }
263
switch (t.capture) {
264
case SubstitutionType.basename: return attributes.basename;
265
case SubstitutionType.dirname: return attributes.dirname;
266
case SubstitutionType.extname: return attributes.extname;
267
case SubstitutionType.capture: return capture || '';
268
}
269
}).join('');
270
}
271
}
272
273