-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathhelpers.ts
1600 lines (1511 loc) · 68.8 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
// Helper functions for dealing with kernels and kernelspecs
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const NamedRegexp = require('named-js-regexp') as typeof import('named-js-regexp');
import * as path from '../platform/vscode-path/path';
import * as uriPath from '../platform/vscode-path/resources';
import * as nbformat from '@jupyterlab/nbformat';
import type { KernelSpec } from '@jupyterlab/services';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cloneDeep = require('lodash/cloneDeep');
import * as url from 'url-parse';
import {
KernelConnectionMetadata,
LocalKernelSpecConnectionMetadata,
LiveRemoteKernelConnectionMetadata,
PythonKernelConnectionMetadata,
IJupyterKernelSpec,
IJupyterSession,
IKernel
} from './types';
import { Uri, workspace } from 'vscode';
import { IWorkspaceService } from '../platform/common/application/types';
import { isCI, PYTHON_LANGUAGE, Telemetry } from '../platform/common/constants';
import { traceError, traceInfo, traceInfoIfCI, traceWarning } from '../platform/logging';
import { getDisplayPath, getFilePath } from '../platform/common/platform/fs-paths';
import { DataScience } from '../platform/common/utils/localize';
import { SysInfoReason } from '../platform/messageTypes';
import { getNormalizedInterpreterPath, getInterpreterHash } from '../platform/pythonEnvironments/info/interpreter';
import { getTelemetrySafeVersion } from '../platform/telemetry/helpers';
import { EnvironmentType, PythonEnvironment } from '../platform/pythonEnvironments/info';
import { fsPathToUri } from '../platform/vscode-path/utils';
import { deserializePythonEnvironment, serializePythonEnvironment } from '../platform/api/pythonApi';
import { JupyterKernelSpec } from './jupyter/jupyterKernelSpec';
import { Resource } from '../platform/common/types';
import { getResourceType } from '../platform/common/utils';
import { sendTelemetryEvent } from '../telemetry';
// https://jupyter-client.readthedocs.io/en/stable/kernels.html
export const connectionFilePlaceholder = '{connection_file}';
// Find the index of the connection file placeholder in a kernelspec
export function findIndexOfConnectionFile(kernelSpec: Readonly<IJupyterKernelSpec>): number {
return kernelSpec.argv.findIndex((arg) => arg.includes(connectionFilePlaceholder));
}
export const jvscIdentifier = '-jvsc-';
export const isDefaultPythonKernelSpecName = /^python\d*.?\d*$/;
/**
* Create a default kernelspec with the given display name.
*/
export function createInterpreterKernelSpec(
interpreter?: PythonEnvironment,
rootKernelFilePath?: Uri
): IJupyterKernelSpec {
const interpreterMetadata = interpreter
? {
path: getFilePath(interpreter.uri)
}
: {};
// This creates a kernel spec for an interpreter. When launched, 'python' argument will map to using the interpreter
// associated with the current resource for launching.
const defaultSpec: KernelSpec.ISpecModel = {
name: getInterpreterKernelSpecName(interpreter),
language: 'python',
display_name: interpreter?.displayName || 'Python 3',
metadata: {
interpreter: interpreterMetadata
},
argv: ['python', '-m', 'ipykernel_launcher', '-f', connectionFilePlaceholder],
env: {},
resources: {}
};
// Generate spec file path if we know where kernel files will go
const specFile =
rootKernelFilePath && defaultSpec.name
? uriPath.joinPath(rootKernelFilePath, defaultSpec.name, 'kernel.json')
: undefined;
return new JupyterKernelSpec(
defaultSpec,
specFile ? getFilePath(specFile) : undefined,
getFilePath(interpreter?.uri),
'registeredByNewVersionOfExt'
);
}
export function cleanEnvironment<T>(spec: T): T {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const copy = cloneDeep(spec) as unknown as { env?: any };
if (copy.env) {
// Scrub the environment of the spec to make sure it has allowed values (they all must be strings)
// See this issue here: https://github.com/microsoft/vscode-python/issues/11749
const keys = Object.keys(copy.env);
keys.forEach((k) => {
if (copy.env) {
const value = copy.env[k];
if (value !== null && value !== undefined) {
copy.env[k] = value.toString();
}
}
});
}
return copy as any;
}
export function getInterpreterHashInMetadata(
notebookMetadata: nbformat.INotebookMetadata | undefined
): string | undefined {
if (!notebookMetadata) {
return;
}
const metadataInterpreter: undefined | { hash?: string } =
'interpreter' in notebookMetadata // In the past we'd store interpreter.hash directly under metadata, but now we store it under metadata.vscode.
? (notebookMetadata.interpreter as undefined | { hash?: string })
: 'vscode' in notebookMetadata &&
notebookMetadata.vscode &&
typeof notebookMetadata.vscode === 'object' &&
'interpreter' in notebookMetadata.vscode
? (notebookMetadata.vscode.interpreter as undefined | { hash?: string })
: undefined;
return metadataInterpreter?.hash;
}
export function isPythonNotebook(metadata?: nbformat.INotebookMetadata) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const kernelSpec = metadata?.kernelspec as any as Partial<IJupyterKernelSpec> | undefined;
if (metadata?.language_info?.name && metadata.language_info.name !== PYTHON_LANGUAGE) {
return false;
}
if (kernelSpec?.name?.includes(PYTHON_LANGUAGE)) {
return true;
}
// Valid notebooks will have a language information in the metadata.
return kernelSpec?.language === PYTHON_LANGUAGE || metadata?.language_info?.name === PYTHON_LANGUAGE;
}
export function rankKernels(
kernels: KernelConnectionMetadata[],
resource: Resource,
notebookMetadata: nbformat.INotebookMetadata | undefined,
preferredInterpreter: PythonEnvironment | undefined,
preferredRemoteKernelId: string | undefined
): KernelConnectionMetadata[] | undefined {
traceInfo(
`Find preferred kernel for ${getDisplayPath(resource)} with metadata ${JSON.stringify(
notebookMetadata || {}
)} & preferred interpreter ${getDisplayPath(preferredInterpreter?.uri)}`
);
if (kernels.length === 0) {
return;
}
// First calculate what the kernel spec would be for our active interpreter
let preferredInterpreterKernelSpec =
preferredInterpreter && findKernelSpecMatchingInterpreter(preferredInterpreter, kernels);
if (preferredInterpreter && !preferredInterpreterKernelSpec) {
const spec = createInterpreterKernelSpec(preferredInterpreter);
preferredInterpreterKernelSpec = <PythonKernelConnectionMetadata>{
kind: 'startUsingPythonInterpreter',
kernelSpec: spec,
interpreter: preferredInterpreter,
id: getKernelId(spec, preferredInterpreter)
};
// Active interpreter isn't in the list of kernels,
// Either because we're using a cached list or Python API isn't returning active interpreter
// along with list of all interpreters.
kernels.push(preferredInterpreterKernelSpec);
}
traceInfoIfCI(`preferredInterpreterKernelSpecIndex = ${preferredInterpreterKernelSpec?.id}`);
// Figure out our possible language from the metadata
const actualNbMetadataLanguage: string | undefined =
notebookMetadata?.language_info?.name.toLowerCase() ||
(notebookMetadata?.kernelspec as undefined | IJupyterKernelSpec)?.language?.toLowerCase();
let possibleNbMetadataLanguage = actualNbMetadataLanguage;
// If the notebook has a language set, remove anything not that language as we don't want to rank those items
kernels = kernels.filter((kernel) => {
if (
possibleNbMetadataLanguage &&
possibleNbMetadataLanguage !== PYTHON_LANGUAGE &&
!notebookMetadata?.kernelspec &&
kernel.kind !== 'connectToLiveRemoteKernel' &&
kernel.kernelSpec.language &&
kernel.kernelSpec.language.toLowerCase() !== possibleNbMetadataLanguage
) {
return false;
}
// Return everything else
return true;
});
// Now perform our big comparison on the kernel list
// Interactive window always defaults to Python kernels.
if (getResourceType(resource) === 'interactive') {
// TODO: Based on the resource, we should be able to find the language.
possibleNbMetadataLanguage = PYTHON_LANGUAGE;
} else {
possibleNbMetadataLanguage =
!notebookMetadata || isPythonNotebook(notebookMetadata) || !possibleNbMetadataLanguage
? PYTHON_LANGUAGE
: (
((notebookMetadata?.kernelspec as any)?.language as string) ||
notebookMetadata?.language_info?.name
)?.toLowerCase();
}
kernels.sort((a, b) =>
compareKernels(
resource,
possibleNbMetadataLanguage,
actualNbMetadataLanguage,
notebookMetadata,
preferredInterpreterKernelSpec,
a,
b,
preferredRemoteKernelId
)
);
return kernels;
}
export function isExactMatch(
kernelConnection: KernelConnectionMetadata,
notebookMetadata: nbformat.INotebookMetadata | undefined,
preferredRemoteKernelId: string | undefined
): boolean {
// Live kernel ID match is always an exact match
if (
kernelConnection.kind === 'connectToLiveRemoteKernel' &&
preferredRemoteKernelId &&
kernelConnection.kernelModel.id === preferredRemoteKernelId
) {
return true;
}
// To get an exact match, we need to have a kernelspec in the metadata
if (!notebookMetadata || !notebookMetadata.kernelspec) {
return false;
}
if (
getInterpreterHashInMetadata(notebookMetadata) &&
interpreterMatchesThatInNotebookMetadata(kernelConnection, notebookMetadata)
) {
// Case: Metadata has interpreter, in this case it should have an interpreter
// and a kernel spec that should fully match, note that in this case matching
// name on a default python kernel spec is ok (as the interpreter hash matches)
return isKernelSpecExactMatch(kernelConnection, notebookMetadata.kernelspec, true);
} else {
// Case: Metadata does not have an interpreter, in this case just full match on the
// kernelspec, but do not accept default python name as valid for an exact match
return isKernelSpecExactMatch(kernelConnection, notebookMetadata.kernelspec, false);
}
}
function isKernelSpecExactMatch(
kernelConnection: KernelConnectionMetadata,
notebookMetadataKernelSpec: nbformat.IKernelspecMetadata,
allowPythonDefaultMatch: boolean
): boolean {
if (kernelConnection.kind === 'connectToLiveRemoteKernel') {
return false;
}
const kernelConnectionKernelSpec = kernelConnection.kernelSpec;
// Get our correct kernelspec name from the connection
const connectionOriginalSpecFile =
kernelConnectionKernelSpec.metadata?.vscode?.originalSpecFile ||
kernelConnectionKernelSpec.metadata?.originalSpecFile;
const connectionKernelSpecName = connectionOriginalSpecFile
? path.basename(path.dirname(connectionOriginalSpecFile))
: kernelConnectionKernelSpec?.name || '';
const connectionInterpreterEnvName = kernelConnection.interpreter?.envName;
const metadataNameIsDefaultName = isDefaultKernelSpec({
argv: [],
display_name: notebookMetadataKernelSpec.display_name,
name: notebookMetadataKernelSpec.name,
executable: ''
});
if (allowPythonDefaultMatch && metadataNameIsDefaultName) {
// If default is allowed (due to interpreter hash match) and the metadata name is a default name then allow the match
return true;
} else if (
!metadataNameIsDefaultName &&
(connectionKernelSpecName === notebookMetadataKernelSpec.name ||
connectionInterpreterEnvName === notebookMetadataKernelSpec.name)
) {
// If default match is not ok, only accept name / display name match for
// non-default kernel specs
return true;
}
return false;
}
export function compareKernels(
_resource: Resource,
possibleNbMetadataLanguage: string | undefined,
actualNbMetadataLanguage: string | undefined,
notebookMetadata: nbformat.INotebookMetadata | undefined,
activeInterpreterConnection: KernelConnectionMetadata | undefined,
a: KernelConnectionMetadata,
b: KernelConnectionMetadata,
preferredRemoteKernelId: string | undefined
) {
// If any ids match the perferred remote kernel id for a live connection that wins over everything
if (
a.kind === 'connectToLiveRemoteKernel' &&
preferredRemoteKernelId &&
a.kernelModel.id === preferredRemoteKernelId
) {
// No need to deal with ties here since ID is unique for this case
return 1;
} else if (
b.kind === 'connectToLiveRemoteKernel' &&
preferredRemoteKernelId &&
b.kernelModel.id === preferredRemoteKernelId
) {
return -1;
}
// Do not sort other live kernel connections (they are at the bottom);
if (a.kind === b.kind && b.kind === 'connectToLiveRemoteKernel') {
return 0;
}
if (a.kind === 'connectToLiveRemoteKernel') {
return -1;
}
if (b.kind === 'connectToLiveRemoteKernel') {
return 1;
}
// Make sure we are comparing lower case here as we have seen C# => c# mis-matches
const aLang = a.kernelSpec.language?.toLowerCase();
const bLang = b.kernelSpec.language?.toLowerCase();
possibleNbMetadataLanguage = possibleNbMetadataLanguage?.toLowerCase();
actualNbMetadataLanguage = actualNbMetadataLanguage?.toLowerCase();
if (!notebookMetadata?.kernelspec) {
if (possibleNbMetadataLanguage) {
if (
possibleNbMetadataLanguage === PYTHON_LANGUAGE &&
aLang === bLang &&
aLang === possibleNbMetadataLanguage
) {
// Fall back to returning the active interpreter (further below).
} else if (aLang === bLang && aLang === possibleNbMetadataLanguage) {
return 0;
} else if (aLang === possibleNbMetadataLanguage) {
return 1;
} else if (bLang === possibleNbMetadataLanguage) {
return -1;
}
}
// Which ever is the default, use that.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
return 0;
}
}
const originalSpecFileA =
a.kernelSpec.metadata?.vscode?.originalSpecFile || a.kernelSpec.metadata?.originalSpecFile;
const originalSpecFileB =
b.kernelSpec.metadata?.vscode?.originalSpecFile || b.kernelSpec.metadata?.originalSpecFile;
const kernelSpecDisplayNameOfA =
a.kernelSpec.metadata?.vscode?.originalDisplayName || a.kernelSpec?.display_name || '';
const kernelSpecDisplayNameOfB =
b.kernelSpec.metadata?.vscode?.originalDisplayName || b.kernelSpec?.display_name || '';
const kernelSpecNameOfA = originalSpecFileA
? path.basename(path.dirname(originalSpecFileA))
: a.kernelSpec?.name || '';
const kernelSpecNameOfB = originalSpecFileB
? path.basename(path.dirname(originalSpecFileB))
: b.kernelSpec?.name || '';
// Special simple comparison algorithm for Non-Python notebooks.
if (possibleNbMetadataLanguage && possibleNbMetadataLanguage !== PYTHON_LANGUAGE) {
// If this isn't a python notebook, then just look at the name & display name.
if (aLang && bLang && aLang !== possibleNbMetadataLanguage && bLang !== possibleNbMetadataLanguage) {
return 0;
} else if (aLang === possibleNbMetadataLanguage && bLang !== possibleNbMetadataLanguage) {
return 1;
} else if (aLang !== possibleNbMetadataLanguage && bLang === possibleNbMetadataLanguage) {
return -1;
} else if (
kernelSpecNameOfA &&
kernelSpecNameOfA === kernelSpecNameOfB &&
kernelSpecDisplayNameOfA === kernelSpecDisplayNameOfB
) {
return 0;
} else if (
kernelSpecNameOfA &&
kernelSpecNameOfA === notebookMetadata.kernelspec?.name &&
kernelSpecDisplayNameOfA === notebookMetadata.kernelspec.display_name
) {
return 1;
} else if (
kernelSpecNameOfB &&
kernelSpecNameOfB === notebookMetadata.kernelspec?.name &&
kernelSpecDisplayNameOfB === notebookMetadata.kernelspec.display_name
) {
return -1;
} else if (kernelSpecNameOfA && kernelSpecNameOfA === notebookMetadata.kernelspec?.name) {
return 1;
} else if (kernelSpecNameOfB && kernelSpecNameOfB === notebookMetadata.kernelspec?.name) {
return -1;
} else if (kernelSpecDisplayNameOfA && kernelSpecDisplayNameOfA === notebookMetadata.kernelspec?.display_name) {
return 1;
} else if (kernelSpecDisplayNameOfB && kernelSpecDisplayNameOfB === notebookMetadata.kernelspec?.display_name) {
return -1;
} else if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
return 0;
}
}
// Sometimes we guess the language information.
// If notebook metadata doesn't have the language information we assume it is Python.
// However if we have a notebook that has kernel information without language information, then we treat them as Python and end up looking for Python kernels.
// Look for exact matches in kernelspecifications, and if found use that.
if (!actualNbMetadataLanguage && possibleNbMetadataLanguage) {
if (
kernelSpecNameOfA &&
kernelSpecDisplayNameOfA &&
kernelSpecNameOfA !== kernelSpecNameOfB &&
kernelSpecDisplayNameOfA !== kernelSpecDisplayNameOfB &&
a.kind === 'startUsingLocalKernelSpec' &&
aLang !== PYTHON_LANGUAGE &&
kernelSpecNameOfA === notebookMetadata.kernelspec.name &&
kernelSpecDisplayNameOfA === notebookMetadata.kernelspec.display_name
) {
// Prefect match.
return 1;
} else if (
kernelSpecNameOfB &&
kernelSpecDisplayNameOfB &&
kernelSpecNameOfA !== kernelSpecNameOfB &&
kernelSpecDisplayNameOfA !== kernelSpecDisplayNameOfB &&
b.kind === 'startUsingLocalKernelSpec' &&
bLang !== PYTHON_LANGUAGE &&
kernelSpecNameOfB === notebookMetadata.kernelspec.name &&
kernelSpecDisplayNameOfB === notebookMetadata.kernelspec.display_name
) {
return -1;
}
}
//
// Everything from here on end, is Python.
//
// Check if one of them is non-python.
if (aLang && bLang) {
if (aLang === bLang) {
if (aLang !== PYTHON_LANGUAGE) {
return 0;
}
} else {
return aLang === PYTHON_LANGUAGE ? 1 : -1;
}
}
if (notebookMetadata?.kernelspec?.name) {
// Check if the name matches against the names in the kernelspecs.
let result = compareKernelSpecOrEnvNames(
a,
b,
kernelSpecNameOfA,
kernelSpecNameOfB,
notebookMetadata,
activeInterpreterConnection
);
if (typeof result === 'number') {
return result;
}
// At this stage when dealing with remote kernels, we cannot match without any confidence.
// Hence give preference to local kernels over remote kernels.
if (a.kind !== 'startUsingRemoteKernelSpec' && b.kind === 'startUsingRemoteKernelSpec') {
return 1;
} else if (a.kind === 'startUsingRemoteKernelSpec' && b.kind !== 'startUsingRemoteKernelSpec') {
return -1;
} else if (a.kind === 'startUsingRemoteKernelSpec' && b.kind === 'startUsingRemoteKernelSpec') {
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
return 0;
}
}
// Check if the name matches against the Python Environment names.
result = compareKernelSpecOrEnvNames(
a,
b,
a.interpreter?.envName || '',
b.interpreter?.envName || '',
notebookMetadata,
activeInterpreterConnection
);
if (typeof result === 'number') {
return result;
}
}
// However if anything is a remote connection give preference to the local connection.
// Because with remotes, we can only best match with the names.
// And we haven't been able to match with the names.
if (a.kind !== 'startUsingRemoteKernelSpec' && b.kind === 'startUsingRemoteKernelSpec') {
return 1;
} else if (a.kind === 'startUsingRemoteKernelSpec' && b.kind !== 'startUsingRemoteKernelSpec') {
return -1;
} else if (a.kind === 'startUsingRemoteKernelSpec' && b.kind === 'startUsingRemoteKernelSpec') {
return 0;
}
const comparisonOfDisplayNames = compareAgainstKernelDisplayNameInNotebookMetadata(a, b, notebookMetadata);
const comparisonOfInterpreter = compareAgainstInterpreterInNotebookMetadata(a, b, notebookMetadata);
// By now we know that the kernelspec name in notebook metadata doesn't match the names of the kernelspecs.
// Nor does it match any of the environment names in the kernels.
// The best we can do is try to match up against the display names & the interpreters
if (comparisonOfDisplayNames >= 0 && comparisonOfInterpreter > 0) {
// Kernel a is a great match for its interpreter over b.
return 1;
} else if (comparisonOfDisplayNames > 0 && comparisonOfInterpreter >= 0) {
// Kernel a is a great match for its display name over b.
return 1;
} else if (comparisonOfDisplayNames <= 0 && comparisonOfInterpreter < 0) {
// Kernel b is a great match for its interpreter over a.
return -1;
} else if (comparisonOfDisplayNames < 0 && comparisonOfInterpreter <= 0) {
// Kernel b is a great match for its display name over a.
return -1;
} else if (comparisonOfDisplayNames < 0 && comparisonOfInterpreter > 0) {
// Ambiguous case, stick to the default behavior.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
return 0;
}
} else if (comparisonOfDisplayNames === 0 && comparisonOfInterpreter === 0) {
// Which ever is the default, use that.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
// Interpreter should trump kernelspec
} else if (a.kind === 'startUsingPythonInterpreter' && b.kind !== 'startUsingPythonInterpreter') {
return 1;
} else if (a.kind !== 'startUsingPythonInterpreter' && b.kind === 'startUsingPythonInterpreter') {
return -1;
}
}
// No idea, stick to the defaults.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
return 0;
}
}
function givePreferenceToStartingWithoutCustomKernelSpec(a: KernelConnectionMetadata, b: KernelConnectionMetadata) {
if (a.kind === 'connectToLiveRemoteKernel' || b.kind === 'connectToLiveRemoteKernel') {
if (a.kind !== 'connectToLiveRemoteKernel') {
return 1;
} else if (b.kind !== 'connectToLiveRemoteKernel') {
return -1;
} else {
return 0;
}
}
const kernelRegA = getKernelRegistrationInfo(a.kernelSpec);
const kernelRegB = getKernelRegistrationInfo(b.kernelSpec);
if (kernelRegA === kernelRegB) {
return 0;
}
if (kernelRegB === 'registeredByNewVersionOfExtForCustomKernelSpec') {
return 1;
}
if (kernelRegA === 'registeredByNewVersionOfExtForCustomKernelSpec') {
return -1;
}
return 0;
}
function compareKernelSpecOrEnvNames(
a: KernelConnectionMetadata,
b: KernelConnectionMetadata,
nameOfA: string,
nameOfB: string,
notebookMetadata: nbformat.INotebookMetadata | undefined,
activeInterpreterConnection: KernelConnectionMetadata | undefined
) {
const comparisonOfDisplayNames = compareAgainstKernelDisplayNameInNotebookMetadata(a, b, notebookMetadata);
const comparisonOfInterpreter = compareAgainstInterpreterInNotebookMetadata(a, b, notebookMetadata);
if (!notebookMetadata?.kernelspec?.name) {
//
} else if (notebookMetadata.kernelspec.name.toLowerCase().match(isDefaultPythonKernelSpecName)) {
const kernelRegA = a.kind !== 'connectToLiveRemoteKernel' ? getKernelRegistrationInfo(a.kernelSpec) : '';
const kernelRegB = b.kind !== 'connectToLiveRemoteKernel' ? getKernelRegistrationInfo(b.kernelSpec) : '';
// Almost all Python kernels match kernel name `python`, `python2` or `python3`.
// When we start kernels using Python interpreter, we store `python` or `python3` in the nb metadata.
// Thus it could match any kernel.
// In such cases we default back to the active interpreter.
// An exception to this is, if we have a display name or interpreter.hash that could match a kernel.
const majorVersion = parseInt(notebookMetadata.kernelspec.name.toLowerCase().replace('python', ''), 10);
if (
majorVersion &&
a.interpreter?.version?.major === b.interpreter?.version?.major &&
a.kind === b.kind &&
comparisonOfDisplayNames === 0 &&
comparisonOfInterpreter === 0
) {
// Both kernels match this version.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
// We're dealing with default kernel (python3), hence start using Python interpreter, not custom kernlespecs.
// Thus iff user has interpreter & a custom kernel spec, then in this case give preference to
// starting with interpreter instead of custom kernelspec.
return givePreferenceToStartingWithoutCustomKernelSpec(a, b);
}
} else if (
majorVersion &&
a.interpreter?.version?.major !== b.interpreter?.version?.major &&
a.interpreter?.version?.major === majorVersion &&
a.kind !== 'startUsingRemoteKernelSpec' &&
comparisonOfDisplayNames >= 0 &&
comparisonOfInterpreter >= 0
) {
return 1;
} else if (
majorVersion &&
a.interpreter?.version?.major !== b.interpreter?.version?.major &&
b.interpreter?.version?.major === majorVersion &&
b.kind !== 'startUsingRemoteKernelSpec' &&
comparisonOfDisplayNames <= 0 &&
comparisonOfInterpreter <= 0
) {
return -1;
} else if (
nameOfA === notebookMetadata.kernelspec.name &&
comparisonOfDisplayNames >= 0 &&
comparisonOfInterpreter >= 0
) {
// Kernel a matches the name and it has a better match for display names & interpreter.
return 1;
} else if (
a.kind === 'startUsingPythonInterpreter' &&
kernelRegA !== 'registeredByNewVersionOfExtForCustomKernelSpec' &&
nameOfA === a.kernelSpec.display_name &&
comparisonOfDisplayNames >= 0 &&
comparisonOfInterpreter >= 0
) {
// Some times the kernel name might not match, as the name might default to the display name of the kernelspec.
// IN such cases check if this kernel a is a python interpreter and not mapping to a custom kernelspec.
// If that's the case then this matches default Python kernels.
return 1;
} else if (
nameOfB === notebookMetadata.kernelspec.name &&
comparisonOfDisplayNames <= 0 &&
comparisonOfInterpreter <= 0
) {
// Kernel b matches the name and it has a better match for display names & interpreter.
return -1;
} else if (
b.kind === 'startUsingPythonInterpreter' &&
kernelRegB !== 'registeredByNewVersionOfExtForCustomKernelSpec' &&
nameOfA === b.kernelSpec.display_name &&
comparisonOfDisplayNames <= 0 &&
comparisonOfInterpreter <= 0
) {
// Some times the kernel name might not match, as the name might default to the display name of the kernelspec.
// IN such cases check if this kernel a is a python interpreter and not mapping to a custom kernelspec.
// If that's the case then this matches default Python kernels.
return 1;
} else if (comparisonOfInterpreter > 0) {
// Clearly kernel a has a better match (at least the interpreter matches).
return 1;
} else if (comparisonOfInterpreter < 0) {
// Clearly kernel b has a better match (at least the interpreter matches).
return -1;
}
} else if (nameOfA === nameOfB && nameOfA === notebookMetadata.kernelspec.name) {
// Names match for both kernels.
// Check which has a better match for interpreter & display name.
if (comparisonOfDisplayNames >= 0 && comparisonOfInterpreter >= 0) {
return 1;
} else if (comparisonOfDisplayNames < 0 && comparisonOfInterpreter < 0) {
return -1;
} else {
// If interpreter matches for a, then use a.
return comparisonOfInterpreter;
}
} else if (nameOfA === notebookMetadata.kernelspec.name) {
// Check which has a better match for interpreter & display name.
if (comparisonOfDisplayNames >= 0 && comparisonOfInterpreter >= 0) {
return 1;
} else if (comparisonOfDisplayNames < 0 && comparisonOfInterpreter < 0) {
return -1;
}
// If kernel a matches the default (active) interpreter connection,
// Then use a, similarly for b.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
// If interpreter matches for a, then use a.
return comparisonOfInterpreter;
}
} else if (nameOfB === notebookMetadata.kernelspec.name) {
// Check which has a better match for interpreter & display name.
if (comparisonOfDisplayNames > 0 && comparisonOfInterpreter > 0) {
// Kernel a has a better match for display name & interpreter, hence
// use that (even though the name doesn't match).
return 1;
} else if (comparisonOfDisplayNames <= 0 && comparisonOfInterpreter <= 0) {
// Kernel a has a better match for name, display name & interpreter, hence
// use that.
return -1;
}
// If kernel a matches the default (active) interpreter connection,
// Then use a, similarly for b.
if (a === activeInterpreterConnection) {
return 1;
} else if (b === activeInterpreterConnection) {
return -1;
} else {
// If interpreter matches for a, then use a.
return comparisonOfInterpreter;
}
}
// None of them match the name.
}
/**
* In the notebook we store a hash of the interpreter.
* Given that hash, compare the two kernels and find the better of the two.
*
* If the user has kernelspec in metadata & the interpreter hash is stored in metadata, then its a great match.
* This is the preferred approach https://github.com/microsoft/vscode-jupyter/issues/5612
*/
function compareAgainstInterpreterInNotebookMetadata(
a: KernelConnectionMetadata,
b: KernelConnectionMetadata,
notebookMetadata?: nbformat.INotebookMetadata
) {
if (a.kind === 'connectToLiveRemoteKernel' && b.kind === 'connectToLiveRemoteKernel') {
return 0;
} else if (a.kind === 'connectToLiveRemoteKernel') {
return -1;
} else if (b.kind === 'connectToLiveRemoteKernel') {
return 1;
}
const kernelRegInfoA = getKernelRegistrationInfo(a.kernelSpec);
const kernelRegInfoB = getKernelRegistrationInfo(b.kernelSpec);
const interpreterMatchesThatInNotebookMetadataA = !!interpreterMatchesThatInNotebookMetadata(a, notebookMetadata);
const interpreterMatchesThatInNotebookMetadataB = !!interpreterMatchesThatInNotebookMetadata(b, notebookMetadata);
if (!interpreterMatchesThatInNotebookMetadataA && !interpreterMatchesThatInNotebookMetadataB) {
// Both don't match.
return 0;
} else if (
interpreterMatchesThatInNotebookMetadataA &&
interpreterMatchesThatInNotebookMetadataB &&
a.kind === b.kind &&
kernelRegInfoA === kernelRegInfoB
) {
// Both are the same.
return 0;
} else if (interpreterMatchesThatInNotebookMetadataA && !interpreterMatchesThatInNotebookMetadataB) {
// a matches and b does not.
return 1;
} else if (!interpreterMatchesThatInNotebookMetadataA && interpreterMatchesThatInNotebookMetadataB) {
// b matches and a does not.
return -1;
}
// Now we know that both kernels point to the same interpreter defined in the notebook metadata.
// Find the best of the two.
if (
a.kind === 'startUsingPythonInterpreter' &&
a.kind !== b.kind &&
kernelRegInfoA !== 'registeredByNewVersionOfExtForCustomKernelSpec'
) {
// Give preference to kernel a that starts using plain python.
return 1;
} else if (
b.kind === 'startUsingPythonInterpreter' &&
b.kind !== a.kind &&
kernelRegInfoB !== 'registeredByNewVersionOfExtForCustomKernelSpec'
) {
// Give preference to kernel b that starts using plain python.
return -1;
} else if (a.kind === 'startUsingPythonInterpreter' && a.kind !== b.kind) {
// Give preference to kernel a that starts using a plain Python for a custom kernelspec.
return 1;
} else if (b.kind === 'startUsingPythonInterpreter' && b.kind !== a.kind) {
// Give preference to kernel b that starts using a plain Python for a custom kernelspec.
return -1;
} else if (a.kind === 'startUsingLocalKernelSpec' && a.kind !== b.kind) {
// Give preference to kernel a that starts using a custom kernelspec python.
return 1;
} else if (b.kind === 'startUsingLocalKernelSpec' && a.kind !== b.kind) {
// Give preference to kernel a that starts using a custom kernelspec python.
return 1;
} else {
return 0;
}
}
/**
* In the notebook we store a display name of the kernelspec.
* Given that display name, compare the two kernels and find the better of the two.
* If the display name matches the display name of the kernelspec its a perfect match,
* If the display name matches the display name of the interpreter its also a match (but not as great as the former).
*/
function compareAgainstKernelDisplayNameInNotebookMetadata(
a: KernelConnectionMetadata,
b: KernelConnectionMetadata,
notebookMetadata?: nbformat.INotebookMetadata
) {
if (a.kind === 'connectToLiveRemoteKernel' && b.kind === 'connectToLiveRemoteKernel') {
return 0;
} else if (a.kind === 'connectToLiveRemoteKernel') {
return -1;
} else if (b.kind === 'connectToLiveRemoteKernel') {
return 1;
}
if (!notebookMetadata?.kernelspec?.display_name) {
return 0;
}
const metadataPointsToADefaultKernelSpec = isDefaultKernelSpec({
argv: [],
display_name: notebookMetadata.kernelspec.display_name,
name: notebookMetadata.kernelspec.name,
executable: ''
});
if (metadataPointsToADefaultKernelSpec) {
// If we're dealing with default kernelspec names, then special handling.
// Sometimes if we have an interpreter a, then the kernelspec name might default to the
// interpreter display name (this is how we generate display names).
// In such cases don't compare the display names of these kernlespecs against the notebook metadata.
const kernelRegA = getKernelRegistrationInfo(a.kernelSpec);
const kernelRegB = getKernelRegistrationInfo(b.kernelSpec);
if (kernelRegA === kernelRegB && a.kind === b.kind) {
// Do nothing.
} else if (
kernelRegA !== 'registeredByNewVersionOfExtForCustomKernelSpec' &&
kernelRegB === 'registeredByNewVersionOfExtForCustomKernelSpec' &&
a.kind === 'startUsingPythonInterpreter'
) {
// Give pref to a
return 1;
} else if (
kernelRegB !== 'registeredByNewVersionOfExtForCustomKernelSpec' &&
kernelRegA === 'registeredByNewVersionOfExtForCustomKernelSpec' &&
b.kind === 'startUsingPythonInterpreter'
) {
// Give pref to a
return -1;
}
// Possible the kernelspec of one of them matches exactly.
if (
a.kernelSpec.metadata?.vscode?.originalDisplayName &&
a.kernelSpec.metadata?.vscode?.originalDisplayName === b.kernelSpec.metadata?.vscode?.originalDisplayName
) {
// Both match.
return 0;
} else if (
a.kernelSpec.metadata?.vscode?.originalDisplayName &&
a.kernelSpec.metadata?.vscode?.originalDisplayName === notebookMetadata.kernelspec.display_name
) {
return 1;
} else if (
b.kernelSpec.metadata?.vscode?.originalDisplayName &&
b.kernelSpec.metadata?.vscode?.originalDisplayName === notebookMetadata.kernelspec.display_name
) {
return -1;
} else {
// Ambiguous case.
return 0;
}
}
if (
a.kernelSpec.display_name === b.kernelSpec.display_name &&
a.kernelSpec.metadata?.vscode?.originalDisplayName === b.kernelSpec.metadata?.vscode?.originalDisplayName
) {
// Both match.
return 0;
} else if (
a.kernelSpec.display_name === notebookMetadata.kernelspec.display_name ||
a.kernelSpec.metadata?.vscode?.originalDisplayName === notebookMetadata.kernelspec.display_name
) {
return 1;
} else if (
b.kernelSpec.display_name === notebookMetadata.kernelspec.display_name ||
b.kernelSpec.metadata?.vscode?.originalDisplayName === notebookMetadata.kernelspec.display_name
) {
return -1;
} else {
return 0;
}
}
/**
* Given an interpreter, find the kernel connection that matches this interpreter.
* & is used to start a kernel using the provided interpreter.
*/
export function findKernelSpecMatchingInterpreter(
interpreter: PythonEnvironment | undefined,
kernels: KernelConnectionMetadata[]
) {
if (!interpreter || kernels.length === 0) {
return;
}
const result = kernels.filter((kernel) => {
return (
kernel.kind === 'startUsingPythonInterpreter' &&
getKernelRegistrationInfo(kernel.kernelSpec) !== 'registeredByNewVersionOfExtForCustomKernelSpec' &&
getInterpreterHash(kernel.interpreter) === getInterpreterHash(interpreter) &&
kernel.interpreter.envName === interpreter.envName
);
});
// if we have more than one match then something is wrong.
if (result.length > 1) {
traceError(`More than one kernel spec matches the interpreter ${interpreter.uri}.`, result);
if (isCI) {
throw new Error('More than one kernelspec matches the intererpreter');
}
}
return result.length ? result[0] : undefined;
}
/**
* Checks whether the kernel connection matches the interpreter defined in the notebook metadata.
*/
function interpreterMatchesThatInNotebookMetadata(
kernelConnection: KernelConnectionMetadata,
notebookMetadata?: nbformat.INotebookMetadata
) {
const interpreterHashInMetadata = getInterpreterHashInMetadata(notebookMetadata);
const interpreterHashForKernel = kernelConnection.interpreter
? getInterpreterHash(kernelConnection.interpreter)
: undefined;
return (
interpreterHashInMetadata &&
(kernelConnection.kind === 'startUsingLocalKernelSpec' ||
kernelConnection.kind === 'startUsingRemoteKernelSpec' ||
kernelConnection.kind === 'startUsingPythonInterpreter') &&
kernelConnection.interpreter &&
interpreterHashForKernel === interpreterHashInMetadata
);
}
export function isDefaultKernelSpec(kernelspec: IJupyterKernelSpec) {
// // When we create kernlespecs, we change the name to include a unique id.
// // We need to look at the name of the original kernelspec that was created on disc.
// // E.g. assume we're loading a kernlespec for a default Python kernel, the name would be `python3`
// // However we give this a completely different name, and at that point its not possible to determine
// // whether this is a default kernel or not.
// // Hence determine the original name baesed on the original kernelspec file.
const originalSpecFile = kernelspec.metadata?.vscode?.originalSpecFile || kernelspec.metadata?.originalSpecFile;
const name = originalSpecFile ? path.basename(path.dirname(originalSpecFile)) : kernelspec.name || '';
const displayName = kernelspec.metadata?.vscode?.originalDisplayName || kernelspec.display_name || '';
// If the user creates a kernelspec with a name `python4` or changes the display
// name of kernel `python3` to `Hello World`, then we'd still treat them as default kernelspecs,