Path: blob/main/src/vs/workbench/contrib/files/common/explorerFileNestingTrie.ts
5241 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45type FilenameAttributes = {6// index.test in index.test.json7basename: string;8// json in index.test.json9extname: string;10// my-folder in my-folder/index.test.json11dirname: string;12};1314/**15* A sort of double-ended trie, used to efficiently query for matches to "star" patterns, where16* a given key represents a parent and may contain a capturing group ("*"), which can then be17* referenced via the token "$(capture)" in associated child patterns.18*19* The generated tree will have at most two levels, as subtrees are flattened rather than nested.20*21* Example:22* The config: [23* [ *.ts , [ $(capture).*.ts ; $(capture).js ] ]24* [ *.js , [ $(capture).min.js ] ] ]25* Nests the files: [ a.ts ; a.d.ts ; a.js ; a.min.js ; b.ts ; b.min.js ]26* As:27* - a.ts => [ a.d.ts ; a.js ; a.min.js ]28* - b.ts => [ ]29* - b.min.ts => [ ]30*/31export class ExplorerFileNestingTrie {32private root = new PreTrie();3334constructor(config: [string, string[]][]) {35for (const [parentPattern, childPatterns] of config) {36for (const childPattern of childPatterns) {37this.root.add(parentPattern, childPattern);38}39}40}4142toString() {43return this.root.toString();44}4546private getAttributes(filename: string, dirname: string): FilenameAttributes {47const lastDot = filename.lastIndexOf('.');48if (lastDot < 1) {49return {50dirname,51basename: filename,52extname: ''53};54} else {55return {56dirname,57basename: filename.substring(0, lastDot),58extname: filename.substring(lastDot + 1)59};60}61}6263nest(files: string[], dirname: string): Map<string, Set<string>> {64const parentFinder = new PreTrie();6566for (const potentialParent of files) {67const attributes = this.getAttributes(potentialParent, dirname);68const children = this.root.get(potentialParent, attributes);69for (const child of children) {70parentFinder.add(child, potentialParent);71}72}7374const findAllRootAncestors = (file: string, seen: Set<string> = new Set()): string[] => {75if (seen.has(file)) { return []; }76seen.add(file);77const attributes = this.getAttributes(file, dirname);78const ancestors = parentFinder.get(file, attributes);79if (ancestors.length === 0) {80return [file];81}8283if (ancestors.length === 1 && ancestors[0] === file) {84return [file];85}8687return ancestors.flatMap(a => findAllRootAncestors(a, seen));88};8990const result = new Map<string, Set<string>>();91for (const file of files) {92let ancestors = findAllRootAncestors(file);93if (ancestors.length === 0) { ancestors = [file]; }94for (const ancestor of ancestors) {95let existing = result.get(ancestor);96if (!existing) { result.set(ancestor, existing = new Set()); }97if (file !== ancestor) {98existing.add(file);99}100}101}102return result;103}104}105106/** Export for test only. */107export class PreTrie {108private value: SufTrie = new SufTrie();109110private map: Map<string, PreTrie> = new Map();111112add(key: string, value: string) {113if (key === '') {114this.value.add(key, value);115} else if (key[0] === '*') {116this.value.add(key, value);117} else {118const head = key[0];119const rest = key.slice(1);120let existing = this.map.get(head);121if (!existing) {122this.map.set(head, existing = new PreTrie());123}124existing.add(rest, value);125}126}127128get(key: string, attributes: FilenameAttributes): string[] {129const results: string[] = [];130results.push(...this.value.get(key, attributes));131132const head = key[0];133const rest = key.slice(1);134const existing = this.map.get(head);135if (existing) {136results.push(...existing.get(rest, attributes));137}138139return results;140}141142toString(indentation = ''): string {143const lines = [];144if (this.value.hasItems) {145lines.push('* => \n' + this.value.toString(indentation + ' '));146}147[...this.map.entries()].map(([key, trie]) =>148lines.push('^' + key + ' => \n' + trie.toString(indentation + ' ')));149return lines.map(l => indentation + l).join('\n');150}151}152153/** Export for test only. */154export class SufTrie {155private star: SubstitutionString[] = [];156private epsilon: SubstitutionString[] = [];157158private map: Map<string, SufTrie> = new Map();159hasItems: boolean = false;160161add(key: string, value: string) {162this.hasItems = true;163if (key === '*') {164this.star.push(new SubstitutionString(value));165} else if (key === '') {166this.epsilon.push(new SubstitutionString(value));167} else {168const tail = key[key.length - 1];169const rest = key.slice(0, key.length - 1);170if (tail === '*') {171throw Error('Unexpected star in SufTrie key: ' + key);172} else {173let existing = this.map.get(tail);174if (!existing) {175this.map.set(tail, existing = new SufTrie());176}177existing.add(rest, value);178}179}180}181182get(key: string, attributes: FilenameAttributes): string[] {183const results: string[] = [];184if (key === '') {185results.push(...this.epsilon.map(ss => ss.substitute(attributes)));186}187if (this.star.length) {188results.push(...this.star.map(ss => ss.substitute(attributes, key)));189}190191const tail = key[key.length - 1];192const rest = key.slice(0, key.length - 1);193const existing = this.map.get(tail);194if (existing) {195results.push(...existing.get(rest, attributes));196}197198return results;199}200201toString(indentation = ''): string {202const lines = [];203if (this.star.length) {204lines.push('* => ' + this.star.join('; '));205}206207if (this.epsilon.length) {208// allow-any-unicode-next-line209lines.push('ε => ' + this.epsilon.join('; '));210}211212[...this.map.entries()].map(([key, trie]) =>213lines.push(key + '$' + ' => \n' + trie.toString(indentation + ' ')));214215return lines.map(l => indentation + l).join('\n');216}217}218219const enum SubstitutionType {220capture = 'capture',221basename = 'basename',222dirname = 'dirname',223extname = 'extname',224}225226const substitutionStringTokenizer = /\$[({](capture|basename|dirname|extname)[)}]/g;227228class SubstitutionString {229230private tokens: (string | { capture: SubstitutionType })[] = [];231232constructor(pattern: string) {233substitutionStringTokenizer.lastIndex = 0;234let token;235let lastIndex = 0;236while (token = substitutionStringTokenizer.exec(pattern)) {237const prefix = pattern.slice(lastIndex, token.index);238this.tokens.push(prefix);239240const type = token[1];241switch (type) {242case SubstitutionType.basename:243case SubstitutionType.dirname:244case SubstitutionType.extname:245case SubstitutionType.capture:246this.tokens.push({ capture: type });247break;248default: throw Error('unknown substitution type: ' + type);249}250lastIndex = token.index + token[0].length;251}252253if (lastIndex !== pattern.length) {254const suffix = pattern.slice(lastIndex, pattern.length);255this.tokens.push(suffix);256}257}258259substitute(attributes: FilenameAttributes, capture?: string): string {260return this.tokens.map(t => {261if (typeof t === 'string') { return t; }262switch (t.capture) {263case SubstitutionType.basename: return attributes.basename;264case SubstitutionType.dirname: return attributes.dirname;265case SubstitutionType.extname: return attributes.extname;266case SubstitutionType.capture: return capture || '';267}268}).join('');269}270}271272273