|
1 | 1 | import * as os from 'os'; |
2 | 2 | import * as path from 'path'; |
3 | | -import { Uri } from 'vscode'; |
| 3 | +import { NotebookCell, NotebookDocument, Uri, workspace } from 'vscode'; |
4 | 4 | import { isWindows } from './platformUtils'; |
5 | 5 |
|
6 | 6 | 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; |
15 | 9 | } |
| 10 | + |
16 | 11 | if (Array.isArray(scope)) { |
| 12 | + // if the scope is an array, all items must be Uri, check each item |
17 | 13 | 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.'); |
19 | 19 | }); |
20 | 20 | } |
| 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 | + } |
21 | 29 | return scope; |
22 | 30 | } |
23 | 31 |
|
| 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 | + |
24 | 60 | export function normalizePath(fsPath: string): string { |
25 | 61 | const path1 = fsPath.replace(/\\/g, '/'); |
26 | 62 | if (isWindows()) { |
|
0 commit comments