Skip to content
This repository was archived by the owner on Nov 18, 2022. It is now read-only.

Commit 3bcdb62

Browse files
committed
Jam some outermost folder fetching logic into a single function
1 parent a170fc0 commit 3bcdb62

File tree

1 file changed

+28
-32
lines changed

1 file changed

+28
-32
lines changed

src/utils/workspace.ts

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -46,43 +46,39 @@ export function nearestParentWorkspace(
4646
}
4747

4848
// This is an intermediate, lazy cache used by `getOuterMostWorkspaceFolder`
49-
// and cleared when VSCode workspaces change.
50-
let _sortedWorkspaceFolders: string[] | undefined;
51-
52-
function sortedWorkspaceFolders(): string[] {
53-
if (!_sortedWorkspaceFolders && workspace.workspaceFolders) {
54-
_sortedWorkspaceFolders = workspace.workspaceFolders
55-
.map(folder => {
56-
let result = folder.uri.toString();
57-
if (result.charAt(result.length - 1) !== '/') {
58-
result = result + '/';
59-
}
60-
return result;
61-
})
62-
.sort((a, b) => {
63-
return a.length - b.length;
64-
});
65-
}
66-
return _sortedWorkspaceFolders || [];
67-
}
49+
// and should be regenerated when VSCode workspaces change.
50+
let _cachedSortedWorkspaceFolders: string[] | undefined;
6851

6952
export function getOuterMostWorkspaceFolder(
7053
folder: WorkspaceFolder,
7154
options?: { cached: boolean },
7255
): WorkspaceFolder {
73-
if (!options || !options.cached) {
74-
_sortedWorkspaceFolders = undefined;
75-
}
56+
const recalculate = !options || !options.cached;
57+
// Sort workspace folders or used already cached result, if possible
58+
const sortedFolders =
59+
!recalculate && _cachedSortedWorkspaceFolders
60+
? _cachedSortedWorkspaceFolders
61+
: (workspace.workspaceFolders || [])
62+
.map(folder => normalizeUriToPathPrefix(folder.uri))
63+
.sort((a, b) => a.length - b.length);
64+
_cachedSortedWorkspaceFolders = sortedFolders;
7665

77-
const sorted = sortedWorkspaceFolders();
78-
for (const element of sorted) {
79-
let uri = folder.uri.toString();
80-
if (uri.charAt(uri.length - 1) !== '/') {
81-
uri = uri + '/';
82-
}
83-
if (uri.startsWith(element)) {
84-
return workspace.getWorkspaceFolder(Uri.parse(element)) || folder;
85-
}
66+
const uri = normalizeUriToPathPrefix(folder.uri);
67+
68+
const outermostPath = sortedFolders.find(prefix => uri.startsWith(prefix));
69+
return outermostPath
70+
? workspace.getWorkspaceFolder(Uri.parse(outermostPath)) || folder
71+
: folder;
72+
}
73+
74+
/**
75+
* Transforms a given URI to a path prefix, namely ensures that each path
76+
* segment ends with a path separator `/`.
77+
*/
78+
function normalizeUriToPathPrefix(uri: Uri): string {
79+
let result = uri.toString();
80+
if (result.charAt(result.length - 1) !== '/') {
81+
result = result + '/';
8682
}
87-
return folder;
83+
return result;
8884
}

0 commit comments

Comments
 (0)