Skip to content

Commit 39e3225

Browse files
authored
Get Notebook Uri from Cell Logic Fix (#312)
1 parent f34f14c commit 39e3225

File tree

1 file changed

+46
-10
lines changed

1 file changed

+46
-10
lines changed

src/common/utils/pathUtils.ts

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,62 @@
11
import * as os from 'os';
22
import * as path from 'path';
3-
import { Uri } from 'vscode';
3+
import { NotebookCell, NotebookDocument, Uri, workspace } from 'vscode';
44
import { isWindows } from './platformUtils';
55

66
export function checkUri(scope?: Uri | Uri[] | string): Uri | Uri[] | string | undefined {
7-
if (scope instanceof Uri) {
8-
if (scope.scheme === 'vscode-notebook-cell') {
9-
return Uri.from({
10-
scheme: 'vscode-notebook',
11-
path: scope.path,
12-
authority: scope.authority,
13-
});
14-
}
7+
if (!scope) {
8+
return undefined;
159
}
10+
1611
if (Array.isArray(scope)) {
12+
// if the scope is an array, all items must be Uri, check each item
1713
return scope.map((item) => {
18-
return checkUri(item) as Uri;
14+
const s = checkUri(item);
15+
if (s instanceof Uri) {
16+
return s;
17+
}
18+
throw new Error('Invalid entry, expected Uri.');
1919
});
2020
}
21+
22+
if (scope instanceof Uri) {
23+
if (scope.scheme === 'vscode-notebook-cell') {
24+
const matchingDoc = workspace.notebookDocuments.find((doc) => findCell(scope, doc));
25+
// If we find a matching notebook document, return the Uri of the cell.
26+
return matchingDoc ? matchingDoc.uri : scope;
27+
}
28+
}
2129
return scope;
2230
}
2331

32+
/**
33+
* Find a notebook document by cell Uri.
34+
*/
35+
export function findCell(cellUri: Uri, notebook: NotebookDocument): NotebookCell | undefined {
36+
// Fragment is not unique to a notebook, hence ensure we compare the path as well.
37+
return notebook.getCells().find((cell) => {
38+
return isEqual(cell.document.uri, cellUri);
39+
});
40+
}
41+
function isEqual(uri1: Uri | undefined, uri2: Uri | undefined): boolean {
42+
if (uri1 === uri2) {
43+
return true;
44+
}
45+
if (!uri1 || !uri2) {
46+
return false;
47+
}
48+
return getComparisonKey(uri1) === getComparisonKey(uri2);
49+
}
50+
51+
function getComparisonKey(uri: Uri): string {
52+
return uri
53+
.with({
54+
path: isWindows() ? uri.path.toLowerCase() : uri.path,
55+
fragment: undefined,
56+
})
57+
.toString();
58+
}
59+
2460
export function normalizePath(fsPath: string): string {
2561
const path1 = fsPath.replace(/\\/g, '/');
2662
if (isWindows()) {

0 commit comments

Comments
 (0)