-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathextension.ts
More file actions
1153 lines (1007 loc) · 60.2 KB
/
Copy pathextension.ts
File metadata and controls
1153 lines (1007 loc) · 60.2 KB
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
/*---------------------------------------------------------------------------------------------
* Licensed to the .NET Foundation under one or more agreements.
* The .NET Foundation licenses this file to you under the MIT license.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import
{
AcquireErrorConfiguration,
AcquisitionInvoker,
callWithErrorHandling,
CommandExecutor,
directoryProviderFactory,
DotnetAcquisitionMissingLinuxDependencies,
DotnetAcquisitionRequested,
DotnetAcquisitionStatusRequested,
DotnetAcquisitionTotalSuccessEvent,
DotnetConditionValidator,
DotnetCoreAcquisitionWorker,
DotnetCoreDependencyInstaller,
DotnetExistingPathResolutionCompleted,
DotnetFindPathCommandInvoked,
DotnetFindPathLookupSetting,
DotnetFindPathMetCondition,
DotnetFindPathNoPathMetCondition,
DotnetFindPathSettingFound,
DotnetHostPathFinder,
DotnetInstall,
DotnetInstallMode,
DotnetInstallType,
DotnetOfflineWarning,
DotnetResolver,
DotnetVersionCategorizedEvent,
DotnetVersionResolutionError,
DotnetVersionSpecRequirement,
enableExtensionTelemetry,
ErrorConfiguration,
EventBasedError,
EventCancellationError,
ExistingPathResolver,
ExtensionConfigurationWorker,
formatIssueUrl,
getInstallIdCustomArchitecture,
getMajor,
getMajorMinor,
GlobalAcquisitionContextMenuOpened,
GlobalInstallerResolver,
IAcquisitionWorkerContext,
IDotnetAcquireContext,
IDotnetAcquireResult,
IDotnetConditionValidator,
IDotnetEnsureDependenciesContext,
IDotnetFindPathContext,
IDotnetListInfo,
IDotnetListVersionsContext,
IDotnetListVersionsResult,
IDotnetLogResult,
IDotnetSearchContext,
IDotnetSearchResult,
IDotnetUninstallContext,
IDotnetVersion,
IEventStream,
IEventStreamContext,
IExtensionContext,
IIssueContext,
InstallationValidator,
InstallRecord,
InvalidUninstallRequest,
IUtilityContext,
JsonInstaller,
LanguageModelToolsRegistrationError,
LinuxVersionResolver,
LocalInstallUpdateService,
LocalMemoryCacheSingleton,
NoExtensionIdProvided,
registerEventStream,
UninstallErrorConfiguration,
UserManualInstallFailure,
UserManualInstallRequested,
UserManualInstallSuccess,
UserManualInstallVersionChosen,
VersionResolver,
VSCodeEnvironment,
VSCodeExtensionContext,
WebRequestWorkerSingleton,
WindowDisplayWorker
} from 'vscode-dotnet-runtime-library';
import { InstallTrackerSingleton } from 'vscode-dotnet-runtime-library/dist/Acquisition/InstallTrackerSingleton';
import { EventStreamTaggingDecorator } from 'vscode-dotnet-runtime-library/dist/EventStream/EventStreamTaggingDecorator';
import { dotnetCoreAcquisitionExtensionId } from './DotnetCoreAcquisitionId';
import { registerLanguageModelTools } from './LanguageModelTools';
import open = require('open');
const packageJson = require('../package.json');
// Extension constants
namespace configKeys
{
export const installTimeoutValue = 'installTimeoutValue';
export const enableTelemetry = 'enableTelemetry';
export const existingPath = 'existingDotnetPath';
export const existingSharedPath = 'sharedExistingDotnetPath'
export const proxyUrl = 'proxyUrl';
export const allowInvalidPaths = 'allowInvalidPaths';
export const cacheTimeToLiveMultiplier = 'cacheTimeToLiveMultiplier';
export const showResetDataCommand = 'showResetDataCommand';
export const suppressOutput = 'suppressOutput';
export const highVerbosity = 'highVerbosity';
export const runtimeUpdateDelaySeconds = 'runtimeUpdateDelaySeconds';
export const enableLanguageModelTools = 'enableLanguageModelTools';
}
namespace commandKeys
{
export const acquire = 'acquire';
export const acquireGlobalSDK = 'acquireGlobalSDK';
export const acquireStatus = 'acquireStatus';
export const uninstall = 'uninstall';
export const findPath = 'findPath';
export const uninstallPublic = 'uninstallPublic'
export const uninstallAll = 'uninstallAll';
export const listVersions = 'listVersions';
export const recommendedVersion = 'recommendedVersion'
export const globalAcquireSDKPublic = 'acquireGlobalSDKPublic';
export const showAcquisitionLog = 'showAcquisitionLog';
export const getAcquisitionLog = 'getAcquisitionLog';
export const ensureDotnetDependencies = 'ensureDotnetDependencies';
export const reportIssue = 'reportIssue';
export const resetData = 'resetData';
export const availableInstalls = 'availableInstalls';
export const resetUpdateTimerInternal = '_resetUpdateTimer';
}
const commandPrefix = 'dotnet';
const configPrefix = 'dotnetAcquisitionExtension';
const displayChannelName = '.NET Install Tool';
const defaultTimeoutValue = 600;
const moreInfoUrl = 'https://github.com/dotnet/vscode-dotnet-runtime/blob/main/Documentation/troubleshooting-runtime.md';
let disableActivationUnderTest = true;
let extensionEventStream: IEventStream | undefined;
let extensionGlobalState: vscode.Memento | undefined;
export function activate(vsCodeContext: vscode.ExtensionContext, extensionContext?: IExtensionContext)
{
// All globalState keys are machine-specific (install paths, session tracking, etc.)
// and must not be synced to other machines or dev containers via Settings Sync.
vsCodeContext.globalState.setKeysForSync?.([]);
if ((process.env.DOTNET_INSTALL_TOOL_UNDER_TEST === 'true' || (vsCodeContext?.extensionMode === vscode.ExtensionMode.Test)) && disableActivationUnderTest)
{
return;
}
// Loading Extension Configuration
const extensionConfiguration = extensionContext !== undefined && extensionContext.extensionConfiguration ?
extensionContext.extensionConfiguration :
vscode.workspace.getConfiguration(configPrefix);
// Reading Extension Configuration
const timeoutValue = extensionConfiguration.get<number>(configKeys.installTimeoutValue);
if (!fs.existsSync(vsCodeContext.globalStoragePath))
{
fs.mkdirSync(vsCodeContext.globalStoragePath, { recursive: true });
}
const resolvedTimeoutSeconds = timeoutValue === undefined ? defaultTimeoutValue : timeoutValue;
const runtimeUpdateDelaySeconds = extensionConfiguration.get<number>(configKeys.runtimeUpdateDelaySeconds) ?? 300;
const runtimeUpdateDelayMs = runtimeUpdateDelaySeconds * 1000;
const proxyLink = extensionConfiguration.get<string>(configKeys.proxyUrl);
const showResetDataCommand = extensionConfiguration.get<boolean>(configKeys.showResetDataCommand);
// Create a cache with the TTL setting that we can only reasonably access from here.
const cacheTimeToLiveMultiplier = Math.abs(Number(extensionConfiguration.get<string>(configKeys.cacheTimeToLiveMultiplier) ?? 1)) ?? 1;
const _localCache = LocalMemoryCacheSingleton.getInstance(cacheTimeToLiveMultiplier);
const allowInvalidPathSetting = extensionConfiguration.get<boolean>(configKeys.allowInvalidPaths);
const suppressOutput = extensionConfiguration.get<boolean>(configKeys.suppressOutput) ?? false;
const highVerbosity = extensionConfiguration.get<boolean>(configKeys.highVerbosity) ?? false;
const isExtensionTelemetryEnabled = enableExtensionTelemetry(extensionConfiguration, configKeys.enableTelemetry);
const displayWorker = extensionContext ? extensionContext.displayWorker : new WindowDisplayWorker();
// Creating Contexts to Execute Under
const utilContext = {
ui: displayWorker,
vsCodeEnv: new VSCodeEnvironment()
}
const vsCodeExtensionContext = new VSCodeExtensionContext(vsCodeContext);
const eventStreamContext = {
displayChannelName,
logPath: vsCodeContext.logPath,
extensionId: dotnetCoreAcquisitionExtensionId,
enableTelemetry: isExtensionTelemetryEnabled,
telemetryReporter: extensionContext ? extensionContext.telemetryReporter : undefined,
showLogCommand: `${commandPrefix}.${commandKeys.showAcquisitionLog}`,
packageJson
} as IEventStreamContext;
const [globalEventStream, outputChannelObserver, loggingObserver,
eventStreamObservers, telemetryObserver, _] = registerEventStream(eventStreamContext, vsCodeExtensionContext, utilContext, suppressOutput, highVerbosity);
const runtimeUpdateDirectoryProvider = directoryProviderFactory(
'runtime', vsCodeContext.globalStoragePath); // Assumption : aspnetcore and runtime directory provider use the same logic, otherwise updates would not be found
const automaticUpdater = new LocalInstallUpdateService(globalEventStream, vsCodeContext.globalState, runtimeUpdateDirectoryProvider,
acquireLocal,
uninstall,
loggingObserver
);
if (!(process.env.DOTNET_INSTALL_TOOL_UNDER_TEST === 'true')) // Don't try to update while testing - this would make tests fail randomly
{
automaticUpdater.ManageInstalls(runtimeUpdateDelayMs).catch((e: any) =>
{
if (!suppressOutput)
{
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
vscode.window.showWarningMessage(`The .NET Runtime may be out of date. An error occurred while checking for updates: ${e?.message ?? JSON.stringify(e)}.`);
}
});
}
// Setting up command-shared classes for Runtime & SDK Acquisition
const existingPathConfigWorker = new ExtensionConfigurationWorker(extensionConfiguration, configKeys.existingPath, configKeys.existingSharedPath);
// Creating API Surfaces
const dotnetAcquireRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.acquire}`, async (commandContext: IDotnetAcquireContext): Promise<IDotnetAcquireResult | undefined> =>
{
return acquireLocal(commandContext);
});
async function acquireLocal(commandContext: IDotnetAcquireContext, ignorePathSetting = false): Promise<IDotnetAcquireResult | undefined>
{
const worker = getAcquisitionWorker();
commandContext.mode = commandContext.mode ?? 'runtime' as DotnetInstallMode;
const mode = commandContext.mode;
const workerContext = getAcquisitionWorkerContext(mode, commandContext);
const dotnetPath = await callWithErrorHandling<Promise<IDotnetAcquireResult>>(async () =>
{
globalEventStream.post(new DotnetAcquisitionRequested(commandContext.version, commandContext.requestingExtensionId ?? 'notProvided', mode, commandContext.installType ?? 'local'));
telemetryObserver?.setAcquisitionContext(workerContext, commandContext);
if (!commandContext.requestingExtensionId)
{
globalEventStream.post(new NoExtensionIdProvided(`No requesting extension id was provided for the request ${commandContext.version}.`));
vscode.window.showWarningMessage(`One of your extensions is attempting to install .NET without providing an extension id.
This install cannot be properly maintained. Please report this to the extension author.`);
}
if (!commandContext.version || commandContext.version === 'latest')
{
throw new EventBasedError('BadContextualVersion',
`Cannot acquire .NET version "${commandContext.version}". Please provide a valid version.`);
}
if (!ignorePathSetting)
{
const existingPath = await resolveExistingPathIfExists(existingPathConfigWorker, commandContext, workerContext, utilContext);
if (existingPath)
{
return existingPath;
}
}
// If a fully specified version (e.g., 8.0.19) is requested and forceUpdate is undefined,
// set forceUpdate to true to skip the existing installation check and install the specific version requested.
if (commandContext.version.split('.').length > 2 && commandContext.forceUpdate === undefined)
{
commandContext.forceUpdate = true;
}
const isOffline = !(await WebRequestWorkerSingleton.getInstance().isOnline(timeoutValue ?? defaultTimeoutValue, globalEventStream));
if (!commandContext.forceUpdate || isOffline)
{
// 3.0 Breaking Change: Don't always return latest .NET runtime by default
// Always use offline install matching the major.minor if it exists, unless forceUpdate is set (forceUpdate enables the legacy behavior of always returning the latest .NET runtime)
const existingOfflinePath = await getExistingInstallOffline(worker, workerContext);
if (existingOfflinePath)
{
return Promise.resolve(existingOfflinePath);
}
}
// Note: This will impact the context object given to the worker and error handler since objects own a copy of a reference in JS.
const runtimeVersionResolver = new VersionResolver(workerContext);
commandContext.version = commandContext.version.split('.')?.length > 2 ? commandContext.version : await runtimeVersionResolver.getFullVersion(commandContext.version, mode);
const acquisitionInvoker = new AcquisitionInvoker(workerContext, utilContext);
return mode === 'aspnetcore' ? worker.acquireLocalASPNET(workerContext, acquisitionInvoker) : worker.acquireLocalRuntime(workerContext, acquisitionInvoker);
}, getIssueContext(existingPathConfigWorker)(commandContext.errorConfiguration, 'acquire', commandContext.version), commandContext.requestingExtensionId, workerContext);
const installationId = getInstallIdCustomArchitecture(commandContext.version, commandContext.architecture, mode, 'local');
const install = {
installId: installationId, version: commandContext.version, installMode: mode, isGlobal: false,
architecture: commandContext.architecture ?? DotnetCoreAcquisitionWorker.defaultArchitecture()
} as DotnetInstall;
if (dotnetPath !== undefined && dotnetPath?.dotnetPath)
{
globalEventStream.post(new DotnetAcquisitionTotalSuccessEvent(commandContext.version, install, commandContext.requestingExtensionId ?? '', dotnetPath.dotnetPath));
}
void loggingObserver.flush();
return dotnetPath;
}
const dotnetAcquireGlobalSDKRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.acquireGlobalSDK}`, async (commandContext: IDotnetAcquireContext): Promise<IDotnetAcquireResult | undefined> =>
{
commandContext.mode = commandContext.mode ?? 'sdk' as DotnetInstallMode;
if (commandContext.requestingExtensionId === undefined)
{
return Promise.reject(new Error('No requesting extension id was provided.'));
}
let fullyResolvedVersion = '';
const workerContext = getAcquisitionWorkerContext(commandContext.mode, commandContext);
const worker = getAcquisitionWorker();
const pathResult = await callWithErrorHandling(async () =>
{
// Warning: Between now and later in this call-stack, the context 'version' is incomplete as it has not been resolved.
// Errors between here and the place where it is resolved cannot be routed to one another.
telemetryObserver?.setAcquisitionContext(workerContext, commandContext);
if (commandContext.version === '' || !commandContext.version)
{
throw new EventCancellationError('BadContextualRuntimeVersionError',
`No version was defined to install.`);
}
globalEventStream.post(new DotnetAcquisitionRequested(commandContext.version, commandContext.requestingExtensionId ?? 'notProvided', commandContext.mode!, commandContext.installType ?? 'global'));
const existingOfflinePath = await getExistingInstallIfOffline(worker, workerContext);
if (existingOfflinePath)
{
return Promise.resolve(existingOfflinePath);
}
const globalInstallerResolver = new GlobalInstallerResolver(workerContext, commandContext.version);
fullyResolvedVersion = await globalInstallerResolver.getFullySpecifiedVersion();
// Reset context to point to the fully specified version so it is not possible for someone to access incorrect data during the install process.
// Note: This will impact the context object given to the worker and error handler since objects own a copy of a reference in JS.
commandContext.version = fullyResolvedVersion;
telemetryObserver?.setAcquisitionContext(workerContext, commandContext);
outputChannelObserver.showOutput();
const dotnetPath = await worker.acquireGlobalSDK(workerContext, globalInstallerResolver);
// setPathEnvVar expects the directory holding the dotnet executable, not the executable file itself.
new CommandExecutor(workerContext, utilContext).setPathEnvVar(path.dirname(dotnetPath.dotnetPath), moreInfoUrl, displayWorker, vsCodeExtensionContext, true);
return dotnetPath;
}, getIssueContext(existingPathConfigWorker)(commandContext.errorConfiguration, commandKeys.acquireGlobalSDK), commandContext.requestingExtensionId, workerContext, commandContext.rethrowError);
const installationId = getInstallIdCustomArchitecture(commandContext.version, commandContext.architecture, commandContext.mode, 'global');
const install = {
installId: installationId, version: commandContext.version, installMode: commandContext.mode, isGlobal: true,
architecture: commandContext.architecture ?? DotnetCoreAcquisitionWorker.defaultArchitecture()
} as DotnetInstall;
if (pathResult !== undefined && pathResult?.dotnetPath)
{
globalEventStream.post(new DotnetAcquisitionTotalSuccessEvent(commandContext.version, install, commandContext.requestingExtensionId ?? '', pathResult.dotnetPath));
}
void loggingObserver.flush();
return pathResult;
});
const dotnetListVersionsRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.listVersions}`,
async (commandContext: IDotnetListVersionsContext | undefined, customWebWorker: WebRequestWorkerSingleton | undefined): Promise<IDotnetListVersionsResult | undefined> =>
{
return getAvailableVersions(commandContext, customWebWorker, false);
});
const dotnetRecommendedVersionRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.recommendedVersion}`,
async (commandContext: IDotnetListVersionsContext | undefined, customWebWorker: WebRequestWorkerSingleton | undefined): Promise<IDotnetListVersionsResult> =>
{
const recommendation = await callWithErrorHandling(async () =>
{
const availableVersions = await getAvailableVersions(commandContext, customWebWorker, true) ?? [];
const activeSupportVersions = availableVersions?.filter((version: IDotnetVersion) => version.supportPhase === 'active');
if (!activeSupportVersions || (activeSupportVersions?.length ?? 0) < 1)
{
const err = new EventCancellationError('DotnetVersionResolutionError', `An active-support version of dotnet couldn't be found. Discovered versions: ${JSON.stringify(availableVersions)}`);
globalEventStream.post(new DotnetVersionResolutionError(err, null));
if (!availableVersions || (availableVersions?.length ?? 0) < 1)
{
return [];
}
else
{
return [availableVersions[0]];
}
}
// The first item will be the newest version.
return [activeSupportVersions[0]];
}, getIssueContext(existingPathConfigWorker)(commandContext?.errorConfiguration, 'acquireStatus'));
return recommendation ?? [];
});
const acquireGlobalSDKPublicRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.globalAcquireSDKPublic}`, async (commandContext: IDotnetAcquireContext | undefined) =>
{
globalEventStream.post(new GlobalAcquisitionContextMenuOpened(`The user has opened the global SDK acquisition context menu.`));
const recommendedVersionResult: IDotnetListVersionsResult = await vscode.commands.executeCommand('dotnet.recommendedVersion', { listRuntimes: false, errorConfiguration: commandContext?.errorConfiguration } as IDotnetListVersionsContext);
globalEventStream.post(new DotnetVersionCategorizedEvent(`Recommended versions: ${JSON.stringify(recommendedVersionResult ?? '')}.`));
const recommendedVersion: string = recommendedVersionResult ? recommendedVersionResult[0]?.version : '';
globalEventStream.post(new DotnetVersionCategorizedEvent(`Recommending version: ${recommendedVersion}.`));
const chosenVersion = (await vscode.window.showInputBox(
{
placeHolder: recommendedVersion,
value: recommendedVersion,
prompt: 'The .NET SDK version. You can use different formats: 5, 3.1, 7.0.3xx, 6.0.201, etc.',
})) ?? recommendedVersion;
globalEventStream.post(new UserManualInstallVersionChosen(`The user has chosen to install the .NET SDK version ${chosenVersion}.`));
try
{
globalEventStream.post(new UserManualInstallRequested(`Starting to install the .NET SDK ${chosenVersion} via a user request.`));
await vscode.commands.executeCommand('dotnet.showAcquisitionLog');
const userCommandContext: IDotnetAcquireContext = { version: chosenVersion, requestingExtensionId: 'user', installType: 'global' };
const acquireResult: IDotnetAcquireResult = await vscode.commands.executeCommand('dotnet.acquireGlobalSDK', userCommandContext);
if (acquireResult && acquireResult?.dotnetPath)
{
globalEventStream.post(new UserManualInstallSuccess(`The .NET SDK ${chosenVersion} was successfully installed.`));
}
}
catch (error)
{
globalEventStream.post(new UserManualInstallFailure((error as Error), `The .NET SDK ${chosenVersion} failed to install. Error: ${(error as Error).toString()}`));
vscode.window.showErrorMessage((error as Error).toString());
}
});
const dotnetAcquireStatusRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.acquireStatus}`, async (commandContext: IDotnetAcquireContext): Promise<IDotnetAcquireResult | undefined> =>
{
const pathResult = await callWithErrorHandling(async () =>
{
commandContext.mode ??= 'runtime' as DotnetInstallMode;
commandContext.architecture ??= DotnetCoreAcquisitionWorker.defaultArchitecture();
commandContext.installType ??= 'local' as DotnetInstallType;
commandContext.requestingExtensionId ??= 'unspecified';
const worker = getAcquisitionWorker();
const workerContext = getAcquisitionWorkerContext(commandContext.mode, commandContext);
globalEventStream.post(new DotnetAcquisitionStatusRequested(commandContext.version, commandContext.requestingExtensionId));
// Caveat : acquireStatus expects only a major.minor, so fully specified versions won't be checked here
const existingOfflinePath = await getExistingInstallOffline(worker, workerContext);
if (existingOfflinePath)
{
return Promise.resolve(existingOfflinePath);
}
const runtimeVersionResolver = new VersionResolver(workerContext);
const resolvedVersion = await runtimeVersionResolver.getFullVersion(commandContext.version, commandContext.mode);
commandContext.version = resolvedVersion;
const dotnetPath = await worker.acquireStatus(workerContext, commandContext.mode);
return dotnetPath;
}, getIssueContext(existingPathConfigWorker)(commandContext.errorConfiguration, 'acquireStatus'));
return pathResult;
});
const dotnetAvailableInstallsRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.availableInstalls}`,
async (commandContext: IDotnetSearchContext): Promise<IDotnetSearchResult[]> =>
{
if (commandContext.mode === undefined || commandContext.requestingExtensionId === undefined)
{
throw new EventCancellationError('BadContextualAvailbleInstallsError', `The dotnet.availableInstalls API request was missing either a mode or requestingExtensionId. Please provide this.`);
}
const pathWasProvided = (commandContext.dotnetExecutablePath ?? '') !== '';
let dotnetExecutablePath = pathWasProvided ? commandContext.dotnetExecutablePath! : 'dotnet';
const searchForInstalls = async (hostPath: string): Promise<IDotnetSearchResult[] | undefined> =>
callWithErrorHandling(async () =>
{
// Bad design: An acquire context is needed to setup the state, but don't want to untangle that in this change.
const fakeAcquireContext = {
version: 'notApplicable',
requestingExtensionId: commandContext.requestingExtensionId,
architecture: commandContext.architecture,
mode: commandContext.mode,
installType: 'local' as DotnetInstallType, // does not matter as we search based on the host path
errorConfiguration: commandContext.errorConfiguration
} as IDotnetAcquireContext;
const workerContext = getAcquisitionWorkerContext(commandContext.mode, fakeAcquireContext);
const dotnetResolver = new DotnetResolver(workerContext, utilContext);
const installsInListForm: IDotnetListInfo[] = await dotnetResolver.getDotnetInstalls(hostPath, commandContext.mode, commandContext.architecture);
return installsInListForm.map((installInfo: IDotnetListInfo) =>
{
return {
mode: installInfo.mode,
version: installInfo.version,
directory: installInfo.directory,
architecture: installInfo.architecture ?? DotnetCoreAcquisitionWorker.defaultArchitecture(),
} as IDotnetSearchResult;
});
}, getIssueContext(existingPathConfigWorker)(commandContext?.errorConfiguration, commandKeys.availableInstalls));
let installs = await searchForInstalls(dotnetExecutablePath);
// When no host path is provided we default to a bare 'dotnet', which relies on the PATH. On some platforms
// (notably macOS GUI launches, where /etc/paths.d is not honored by the extension host process) the host is
// not on the PATH even though .NET is installed, so the search finds nothing on the first try. In that case,
// reuse the shared dotnet.findPath logic, which locates the host independently of the PATH (e.g. via the
// known install locations on disk), and retry the search with the discovered host path. This is opt-in via
// fallbackToFindPathInstalls because findPath may return non system-level paths, so enabling it can change
// which installs are returned; defaulting it off preserves the original behavior for existing callers.
if ((installs?.length ?? 0) === 0 && !pathWasProvided && commandContext.fallbackToFindPathInstalls === true)
{
const findPathContext: IDotnetFindPathContext = {
acquireContext: {
// We only need *a* host that has installs of the requested mode; accept any version it reports.
version: '1.0',
requestingExtensionId: commandContext.requestingExtensionId,
architecture: commandContext.architecture ?? DotnetCoreAcquisitionWorker.defaultArchitecture(),
mode: commandContext.mode,
installType: 'global' as DotnetInstallType,
errorConfiguration: commandContext.errorConfiguration,
} as IDotnetAcquireContext,
versionSpecRequirement: 'greater_than_or_equal',
};
const foundHost = await vscode.commands.executeCommand<IDotnetAcquireResult | undefined>(`${commandPrefix}.${commandKeys.findPath}`, findPathContext);
if (foundHost?.dotnetPath && foundHost.dotnetPath !== dotnetExecutablePath)
{
dotnetExecutablePath = foundHost.dotnetPath;
installs = await searchForInstalls(dotnetExecutablePath);
}
}
if ((installs?.length ?? 0) > 0)
{
await InstallTrackerSingleton.getInstance(globalEventStream, vsCodeContext.globalState).markInstallAsInUse(dotnetExecutablePath);
}
return installs ?? [];
});
const resetDataPublicRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.resetData}`, async () =>
{
const uninstallContext: IDotnetUninstallContext = {
errorConfiguration: UninstallErrorConfiguration.DisplayAllErrorPopups,
};
return uninstallAll(uninstallContext);
});
const resetUpdateTimerInternalRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.resetUpdateTimerInternal}`, async () =>
{
await vsCodeContext.globalState.update('dotnet.latestUpdateDate', undefined);
return vsCodeContext.globalState.get<Date>('dotnet.latestUpdateDate');
});
const dotnetUninstallPublicRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.uninstallPublic}`, async () =>
{
const existingInstalls: InstallRecord[] = await InstallTrackerSingleton.getInstance(globalEventStream, vsCodeContext.globalState).getExistingInstalls(directoryProviderFactory(
'runtime', vsCodeContext.globalStoragePath));
const menuItems = existingInstalls?.sort(
function (x: InstallRecord, y: InstallRecord): number
{
if (x.dotnetInstall.installMode === y.dotnetInstall.installMode)
{
return x.dotnetInstall.version.localeCompare(y.dotnetInstall.version);
}
return x.dotnetInstall.installMode.localeCompare(y.dotnetInstall.installMode);
})?.map(install =>
{
return {
label: `.NET ${(install.dotnetInstall.installMode === 'sdk' ? 'SDK' : install.dotnetInstall.installMode === 'runtime' ? 'Runtime' : 'ASP.NET Core Runtime')} ${install.dotnetInstall.version}`,
description: `${install.dotnetInstall.architecture ?? ''} | ${install.dotnetInstall.isGlobal ? 'machine-wide' : 'vscode-local'}`,
detail: install.installingExtensions.some(x => x !== null) ? `Used by ${install.installingExtensions.join(', ')}` : ``,
iconPath: install.dotnetInstall.isGlobal ? new vscode.ThemeIcon('shield') : new vscode.ThemeIcon('trash'),
internalId: install.dotnetInstall.installId
}
});
if ((menuItems?.length ?? 0) < 1)
{
vscode.window.showInformationMessage('No .NET installations were found to uninstall.');
return;
}
const chosenVersion = await vscode.window.showQuickPick(menuItems, { placeHolder: 'Select a version to uninstall.' });
if (chosenVersion)
{
const installRecord: InstallRecord = existingInstalls.find(install => install.dotnetInstall.installId === chosenVersion.internalId)!;
if (!installRecord || !installRecord?.dotnetInstall?.version || !installRecord?.dotnetInstall?.installMode)
{
return;
}
const selectedInstall: DotnetInstall = installRecord.dotnetInstall;
let canContinue = true;
const uninstallWillBreakSomething = !(await InstallTrackerSingleton.getInstance(globalEventStream, vsCodeContext.globalState).installHasNoDependents(selectedInstall, directoryProviderFactory(
'runtime', vsCodeContext.globalStoragePath), true));
const yes = `Continue`;
if (uninstallWillBreakSomething)
{
const brokenExtensions = installRecord.installingExtensions.some(x => x !== null) ? installRecord.installingExtensions.join(', ') : 'extensions such as C# or C# DevKit';
const pick = await vscode.window.showWarningMessage(
`Uninstalling .NET ${selectedInstall.version} will likely cause ${brokenExtensions} to stop functioning properly. Do you still wish to continue?`, { modal: true }, yes);
canContinue = pick === yes;
}
if (!canContinue)
{
return;
}
const commandContext: IDotnetAcquireContext =
{
version: selectedInstall.version,
mode: selectedInstall.installMode,
installType: selectedInstall.isGlobal ? 'global' : 'local',
architecture: selectedInstall.architecture,
requestingExtensionId: 'user'
}
outputChannelObserver.showOutput();
return uninstall(commandContext, true);
}
});
/**
* @returns 0 on success. Error string if not.
*/
const dotnetUninstallRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.uninstall}`, async (commandContext: IDotnetAcquireContext | undefined): Promise<string> =>
{
return uninstall(commandContext);
});
const dotnetForceUpdateRegistration = vscode.commands.registerCommand(`${commandPrefix}.forceUpdate`, async (commandContext: IDotnetAcquireContext): Promise<void> =>
{
return automaticUpdater.ManageInstalls(0).catch((e: any) => {});
});
/**
* @param commandContext The context of the request to find the dotnet path.
* We wrap an AcquisitionContext which must include the version, requestingExtensionId, architecture of .NET desired, and mode.
* The architecture should be of the node format ('x64', 'x86', 'arm64', etc.)
*
* @returns the path to the dotnet executable as an IDotnetAcquireResult (or undefined), if one can be found. This should be the true path to the executable. undefined if none can be found.
* Before version 2.2.2, the result could be a string, undefined, or an IDotnetAcquireResult. This was changed to be more consistent with the rest of the APIs.
*
* @remarks Priority Order for path lookup:
* VSCode Setting -> PATH -> Realpath of PATH -> DOTNET_ROOT (Emulation DOTNET_ROOT if set first)
*
* This accounts for pmc installs, snap installs, bash configurations, and other non-standard installations such as homebrew.
*/
const dotnetFindPathRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.findPath}`, async (commandContext: IDotnetFindPathContext): Promise<IDotnetAcquireResult | undefined> =>
{
const findPathResult = await callWithErrorHandling<Promise<IDotnetAcquireResult | undefined>>(async () =>
{
globalEventStream.post(new DotnetFindPathCommandInvoked(`The find path command was invoked.`, commandContext));
if (!commandContext.acquireContext.mode || !commandContext.acquireContext.requestingExtensionId || !commandContext.acquireContext.version || !commandContext.acquireContext.architecture)
{
throw new EventCancellationError('BadContextualFindPathError', `The find path request was missing required information: a mode, version, architecture, and requestingExtensionId.`);
}
const requestedArchitecture = commandContext.acquireContext.architecture;
globalEventStream.post(new DotnetFindPathLookupSetting(`Looking up vscode setting.`));
const workerContext = getAcquisitionWorkerContext(commandContext.acquireContext.mode, commandContext.acquireContext);
const existingPath = await resolveExistingPathIfExists(existingPathConfigWorker, commandContext.acquireContext, workerContext, utilContext, commandContext.versionSpecRequirement);
// The setting is not intended to be used as the SDK, only the runtime for extensions to run on. Ex: PowerShell policy doesn't allow us to install the runtime, let users set the path manually.
if (existingPath && commandContext.acquireContext.mode !== 'sdk')
{
// We don't need to validate the existing path as it gets validated + tracked in the lookup logic already.
globalEventStream.post(new DotnetFindPathSettingFound(`Found vscode setting.`));
void loggingObserver.flush();
return existingPath;
}
const validator = new DotnetConditionValidator(workerContext, utilContext);
const finder = new DotnetHostPathFinder(workerContext, utilContext);
const dotnetOnShellSpawn = (await finder.findDotnetFastFromListOnly(requestedArchitecture)) ?? '';
if (dotnetOnShellSpawn)
{
const validatedShellSpawn = await getPathIfValid(dotnetOnShellSpawn, validator, commandContext);
if (validatedShellSpawn)
{
void loggingObserver.flush();
return { dotnetPath: validatedShellSpawn };
}
}
const dotnetsOnPATH = await finder.findRawPathEnvironmentSetting(true, requestedArchitecture);
for (const dotnetPath of dotnetsOnPATH ?? [])
{
const validatedPATH = await getPathIfValid(dotnetPath, validator, commandContext);
if (validatedPATH)
{
void loggingObserver.flush();
return { dotnetPath: validatedPATH };
}
}
const dotnetsOnRealPATH = await finder.findRealPathEnvironmentSetting(true, requestedArchitecture);
for (const dotnetPath of dotnetsOnRealPATH ?? [])
{
const validatedRealPATH = await getPathIfValid(dotnetPath, validator, commandContext);
if (validatedRealPATH)
{
void loggingObserver.flush();
return { dotnetPath: validatedRealPATH };
}
}
const dotnetOnROOT = await finder.findDotnetRootPath(commandContext.acquireContext.architecture);
const validatedRoot = await getPathIfValid(dotnetOnROOT, validator, commandContext);
if (validatedRoot)
{
void loggingObserver.flush();
return { dotnetPath: validatedRoot };
}
if (commandContext.acquireContext.mode !== 'sdk' && !commandContext.disableLocalLookup)
{
const extensionManagedRuntimeRecordPaths = await finder.findExtensionManagedRuntimes();
const filteredExtensionManagedRuntimeRecordPaths = validator.filterValidPaths(extensionManagedRuntimeRecordPaths, commandContext);
for (const dotnetPath of filteredExtensionManagedRuntimeRecordPaths ?? [])
{
const validatedExistingManagedPath = await getPathIfValid(dotnetPath.path, validator, commandContext);
if (validatedExistingManagedPath)
{
void loggingObserver.flush();
return { dotnetPath: dotnetPath.path };
}
}
}
const dotnetOnHostfxrRecord = await finder.findHostInstallPaths(commandContext.acquireContext.architecture);
for (const dotnetPath of dotnetOnHostfxrRecord ?? [])
{
const validatedHostfxr = await getPathIfValid(dotnetPath, validator, commandContext);
if (validatedHostfxr && process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR !== 'true')
{
void loggingObserver.flush();
return { dotnetPath: validatedHostfxr };
}
}
void loggingObserver.flush();
globalEventStream.post(new DotnetFindPathNoPathMetCondition(`Could not find a single host path that met the conditions.
existingPath : ${existingPath?.dotnetPath}
onPath : ${JSON.stringify(dotnetsOnPATH)}
onRealPath : ${JSON.stringify(dotnetsOnRealPATH)}
onRoot : ${dotnetOnROOT}
onHostfxrRecord : ${JSON.stringify(dotnetOnHostfxrRecord)}
Requirement:
${JSON.stringify(commandContext)}`));
return undefined;
}, getIssueContext(existingPathConfigWorker)(commandContext?.acquireContext?.errorConfiguration, commandKeys.findPath));
return findPathResult;
});
async function getPathIfValid(candidatePath: string | undefined, validator: IDotnetConditionValidator, commandContext: IDotnetFindPathContext): Promise<string | undefined>
{
if (candidatePath)
{
const validated = await validator.dotnetMeetsRequirement(candidatePath, commandContext);
if (validated)
{
globalEventStream.post(new DotnetFindPathMetCondition(`${candidatePath} met the conditions.`));
await InstallTrackerSingleton.getInstance(globalEventStream, vsCodeContext.globalState).markInstallAsInUse(candidatePath);
return candidatePath;
}
}
return undefined;
}
async function uninstall(commandContext: IDotnetAcquireContext | undefined, force = false, onlyCheckLiveDependents = false): Promise<string>
{
let result = '1';
// Create workerContext early if we have enough info (for error handling context)
// Wrapped in try-catch to avoid unhandled exceptions if context creation fails
let workerContext: IAcquisitionWorkerContext | undefined;
try
{
workerContext = commandContext?.mode && commandContext?.requestingExtensionId
? getAcquisitionWorkerContext(commandContext.mode, commandContext)
: undefined;
}
catch
{
// If context creation fails, continue without it - errors will still be handled
workerContext = undefined;
}
await callWithErrorHandling(async () =>
{
if (!commandContext?.version || !commandContext?.installType || !commandContext?.mode || !commandContext?.requestingExtensionId)
{
const error = new EventCancellationError('InvalidUninstallRequest', `The caller ${commandContext?.requestingExtensionId} did not properly submit an uninstall request.
Please include the mode, installType, version, and extensionId.`);
globalEventStream.post(new InvalidUninstallRequest(error as Error));
throw error;
}
else
{
const worker = getAcquisitionWorker();
// Use the pre-created workerContext if available, otherwise create it
const ctx = workerContext ?? getAcquisitionWorkerContext(commandContext.mode, commandContext);
if (commandContext.installType === 'local' && !force && !(onlyCheckLiveDependents && commandContext.version.split('.').length > 1)) // if using force mode, we are also using the UI, which passes the fully specified version to uninstall only
{
const versionResolver = new VersionResolver(ctx);
const resolvedVersion = await versionResolver.getFullVersion(commandContext.version, commandContext.mode);
commandContext.version = resolvedVersion;
}
const installationId = getInstallIdCustomArchitecture(commandContext.version, commandContext.architecture, commandContext.mode, commandContext.installType);
const install = {
installId: installationId, version: commandContext.version, installMode: commandContext.mode, isGlobal: commandContext.installType === 'global',
architecture: commandContext.architecture ?? DotnetCoreAcquisitionWorker.defaultArchitecture()
} as DotnetInstall;
if (commandContext.installType === 'local')
{
result = await worker.uninstallLocal(ctx, install, force, false, onlyCheckLiveDependents);
}
else
{
const globalInstallerResolver = new GlobalInstallerResolver(ctx, commandContext.version);
result = await worker.uninstallGlobal(ctx, install, globalInstallerResolver, force);
}
// A non-zero (and non-empty) result code means the uninstall did not succeed. Throw from inside the
// callWithErrorHandling callback so the failure goes through the standard error handling path
// (failure event posting, telemetry, and popups) instead of being reported as a success, and is then
// rethrown consistently when rethrowError is requested (e.g. for the LLM tools).
if (result !== '0' && result !== '')
{
throw new Error(`Uninstall of .NET ${commandContext.version} did not succeed (code ${result}). The uninstaller may have been cancelled, blocked by another install in progress, or require manual removal.`);
}
}
}, getIssueContext(existingPathConfigWorker)(commandContext?.errorConfiguration, 'uninstall'), commandContext?.requestingExtensionId, workerContext, commandContext?.rethrowError);
return result;
}
const dotnetUninstallAllRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.uninstallAll}`, async (commandContext: IDotnetUninstallContext | undefined) =>
{
return uninstallAll(commandContext);
});
async function uninstallAll(commandContext: IDotnetUninstallContext | undefined): Promise<number>
{
await callWithErrorHandling(async () =>
{
const mode = 'runtime' as DotnetInstallMode;
const worker = getAcquisitionWorker();
const installDirectoryProvider = directoryProviderFactory(mode, vsCodeContext.globalStoragePath);
await worker.uninstallAll(globalEventStream, installDirectoryProvider.getStoragePath(), vsCodeContext.globalState);
},
getIssueContext(existingPathConfigWorker)(commandContext ? commandContext.errorConfiguration : undefined, 'uninstallAll')
);
return Promise.resolve(0);
}
const showOutputChannelRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.showAcquisitionLog}`, () => outputChannelObserver.showOutput());
const getAcquisitionLogRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.getAcquisitionLog}`, async (): Promise<IDotnetLogResult> =>
{
// Flush any buffered log entries so the file on disk reflects the latest state.
await loggingObserver.flush();
return { logPath: loggingObserver.getFileLocation() };
});
const ensureDependenciesRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.ensureDotnetDependencies}`, async (commandContext: IDotnetEnsureDependenciesContext) =>
{
await callWithErrorHandling(async () =>
{
if (os.platform() !== 'linux')
{
// We can't handle installing dependencies for anything other than Linux
return;
}
// commandContext.arguments is either the dotnet process args (string[]) or a SpawnSync options object.
// Use the 3-arg overload (empty args + options) for the options case so the two paths are distinct.
const result = Array.isArray(commandContext.arguments)
? cp.spawnSync(commandContext.command, commandContext.arguments)
: cp.spawnSync(commandContext.command, [], commandContext.arguments);
const installer = new DotnetCoreDependencyInstaller();
if (installer.signalIndicatesMissingLinuxDependencies(result.signal!))
{
globalEventStream.post(new DotnetAcquisitionMissingLinuxDependencies());
await installer.promptLinuxDependencyInstall('Failed to run .NET runtime.');
}
}, getIssueContext(existingPathConfigWorker)(commandContext.errorConfiguration, 'ensureDependencies'));
});
const reportIssueRegistration = vscode.commands.registerCommand(`${commandPrefix}.${commandKeys.reportIssue}`, async () =>
{
const [url, issueBody] = formatIssueUrl(undefined, getIssueContext(existingPathConfigWorker)(AcquireErrorConfiguration.DisableErrorPopups, 'reportIssue'));
await vscode.env.clipboard.writeText(issueBody);
open(url).catch(() => {});
});
// Helper Functions
async function resolveExistingPathIfExists(configResolver: ExtensionConfigurationWorker, commandContext: IDotnetAcquireContext,
workerContext: IAcquisitionWorkerContext, utilityContext: IUtilityContext, requirement?: DotnetVersionSpecRequirement): Promise<IDotnetAcquireResult | null>
{
const existingPathResolver = new ExistingPathResolver(workerContext, utilityContext);
const existingPath = await existingPathResolver.resolveExistingPath(configResolver.getAllPathConfigurationValues(), commandContext.requestingExtensionId, displayWorker, requirement);
if (existingPath)
{
globalEventStream.post(new DotnetExistingPathResolutionCompleted(existingPath.dotnetPath));
return new Promise((resolve) =>
{
resolve(existingPath);
});
}
return new Promise((resolve) =>
{
resolve(null);
});
}
const getAvailableVersions = async (commandContext: IDotnetListVersionsContext | undefined,
customWebWorker: WebRequestWorkerSingleton | undefined, onRecommendationMode: boolean): Promise<IDotnetListVersionsResult | undefined> =>
{
const mode = 'sdk' as DotnetInstallMode;
const workerContext = getVersionResolverContext(mode, 'global', commandContext?.errorConfiguration);
const customVersionResolver = new VersionResolver(workerContext, customWebWorker);
if (os.platform() !== 'linux' || !onRecommendationMode)
{
const versionsResult = await callWithErrorHandling(async () =>
{
return customVersionResolver.GetAvailableDotnetVersions(commandContext);
}, getIssueContext(existingPathConfigWorker)(commandContext?.errorConfiguration, 'getAvailableVersions'));
return versionsResult;
}
else
{
const linuxResolver = new LinuxVersionResolver(workerContext, utilContext);
try
{
const suggestedVersion = await linuxResolver.getRecommendedDotnetVersion('sdk' as DotnetInstallMode);
const osAgnosticVersionData = await getAvailableVersions(commandContext, customWebWorker, !onRecommendationMode);
const resolvedSupportPhase = osAgnosticVersionData?.find((version: IDotnetVersion) =>
getMajorMinor(version.version, globalEventStream, workerContext) === getMajorMinor(suggestedVersion, globalEventStream, workerContext))?.supportPhase ?? 'active';
// Assumption : The newest version is 'active' support, but we can't guarantee that.
// If the linux version is too old it will eventually support no active versions of .NET, which would cause a failure.
// The best we can give it is the newest working version, which is the most likely to be supported, and mark it as active so we can use it.
return [
{
version: suggestedVersion, channelVersion: `${getMajorMinor(suggestedVersion, globalEventStream, workerContext)}`,
supportStatus: Number(getMajor(suggestedVersion, globalEventStream, workerContext)) % 2 === 0 ? 'lts' : 'sts',
supportPhase: resolvedSupportPhase
}
];
}
catch (error: any)
{
return [];
}
}
}
/**