-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcondaUtils.ts
More file actions
1491 lines (1351 loc) · 53.1 KB
/
condaUtils.ts
File metadata and controls
1491 lines (1351 loc) · 53.1 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
import * as fse from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import {
CancellationError,
CancellationToken,
l10n,
LogOutputChannel,
ProgressLocation,
QuickInputButtons,
QuickPickItem,
ThemeIcon,
Uri,
} from 'vscode';
import which from 'which';
import {
EnvironmentManager,
Package,
PackageManagementOptions,
PackageManager,
PythonCommandRunConfiguration,
PythonEnvironment,
PythonEnvironmentApi,
PythonEnvironmentInfo,
PythonProject,
} from '../../api';
import { spawnProcess } from '../../common/childProcess.apis';
import { ENVS_EXTENSION_ID, EXTENSION_ROOT_DIR } from '../../common/constants';
import { showErrorMessageWithLogs } from '../../common/errors/utils';
import { Common, CondaStrings, PackageManagement, Pickers } from '../../common/localize';
import { traceError, traceInfo, traceVerbose, traceWarn } from '../../common/logging';
import { getWorkspacePersistentState } from '../../common/persistentState';
import { pickProject } from '../../common/pickers/projects';
import { StopWatch } from '../../common/stopWatch';
import { createDeferred } from '../../common/utils/deferred';
import { untildify } from '../../common/utils/pathUtils';
import { isWindows } from '../../common/utils/platformUtils';
import {
showErrorMessage,
showInputBoxWithButtons,
showQuickPickWithButtons,
withProgress,
} from '../../common/window.apis';
import { getConfiguration } from '../../common/workspace.apis';
import { ShellConstants } from '../../features/common/shellConstants';
import { quoteArgs, quoteStringIfNecessary } from '../../features/execution/execUtils';
import {
isNativeEnvInfo,
NativeEnvInfo,
NativeEnvManagerInfo,
NativePythonEnvironmentKind,
NativePythonFinder,
} from '../common/nativePythonFinder';
import { selectFromCommonPackagesToInstall } from '../common/pickers';
import { Installable } from '../common/types';
import { shortVersion, sortEnvironments } from '../common/utils';
import { CondaEnvManager } from './condaEnvManager';
import { getCondaHookPs1Path, getLocalActivationScript, ShellCondaInitStatus } from './condaSourcingUtils';
import { createStepBasedCondaFlow } from './condaStepBasedFlow';
export const CONDA_PATH_KEY = `${ENVS_EXTENSION_ID}:conda:CONDA_PATH`;
export const CONDA_PREFIXES_KEY = `${ENVS_EXTENSION_ID}:conda:CONDA_PREFIXES`;
export const CONDA_WORKSPACE_KEY = `${ENVS_EXTENSION_ID}:conda:WORKSPACE_SELECTED`;
export const CONDA_GLOBAL_KEY = `${ENVS_EXTENSION_ID}:conda:GLOBAL_SELECTED`;
let condaPath: string | undefined;
export async function clearCondaCache(): Promise<void> {
condaPath = undefined;
prefixes = undefined;
}
async function setConda(conda: string): Promise<void> {
condaPath = conda;
const state = await getWorkspacePersistentState();
await state.set(CONDA_PATH_KEY, conda);
}
export function getCondaPathSetting(): string | undefined {
const config = getConfiguration('python');
const value = config.get<string>('condaPath');
return value && typeof value === 'string' ? untildify(value) : value;
}
export async function getCondaForWorkspace(fsPath: string): Promise<string | undefined> {
if (process.env.CONDA_PREFIX) {
return process.env.CONDA_PREFIX;
}
const state = await getWorkspacePersistentState();
const data: { [key: string]: string } | undefined = await state.get(CONDA_WORKSPACE_KEY);
if (data) {
try {
return data[fsPath];
} catch {
return undefined;
}
}
return undefined;
}
export async function setCondaForWorkspace(fsPath: string, condaEnvPath: string | undefined): Promise<void> {
const state = await getWorkspacePersistentState();
const data: { [key: string]: string } = (await state.get(CONDA_WORKSPACE_KEY)) ?? {};
if (condaEnvPath) {
data[fsPath] = condaEnvPath;
} else {
delete data[fsPath];
}
await state.set(CONDA_WORKSPACE_KEY, data);
}
export async function setCondaForWorkspaces(fsPath: string[], condaEnvPath: string | undefined): Promise<void> {
const state = await getWorkspacePersistentState();
const data: { [key: string]: string } = (await state.get(CONDA_WORKSPACE_KEY)) ?? {};
fsPath.forEach((s) => {
if (condaEnvPath) {
data[s] = condaEnvPath;
} else {
delete data[s];
}
});
await state.set(CONDA_WORKSPACE_KEY, data);
}
export async function getCondaForGlobal(): Promise<string | undefined> {
const state = await getWorkspacePersistentState();
return await state.get(CONDA_GLOBAL_KEY);
}
export async function setCondaForGlobal(condaEnvPath: string | undefined): Promise<void> {
const state = await getWorkspacePersistentState();
await state.set(CONDA_GLOBAL_KEY, condaEnvPath);
}
async function findConda(): Promise<readonly string[] | undefined> {
try {
return await which('conda', { all: true });
} catch {
return undefined;
}
}
async function getCondaExecutable(native?: NativePythonFinder): Promise<string> {
if (condaPath) {
if (await fse.pathExists(untildify(condaPath))) {
traceInfo(`Using conda from cache: ${condaPath}`);
return untildify(condaPath);
}
}
const state = await getWorkspacePersistentState();
condaPath = await state.get<string>(CONDA_PATH_KEY);
if (condaPath) {
if (await fse.pathExists(untildify(condaPath))) {
traceInfo(`Using conda from persistent state: ${condaPath}`);
return untildify(condaPath);
}
}
const paths = await findConda();
if (paths && paths.length > 0) {
for (let i = 0; i < paths.length; i++) {
condaPath = paths[i];
if (await fse.pathExists(untildify(condaPath))) {
traceInfo(`Using conda from PATH: ${condaPath}`);
await state.set(CONDA_PATH_KEY, condaPath);
return condaPath;
}
}
}
if (native) {
const data = await native.refresh(false);
const managers = data
.filter((e) => !isNativeEnvInfo(e))
.map((e) => e as NativeEnvManagerInfo)
.filter((e) => e.tool.toLowerCase() === 'conda');
if (managers.length > 0) {
for (let i = 0; i < managers.length; i++) {
condaPath = managers[i].executable;
if (await fse.pathExists(untildify(condaPath))) {
traceInfo(`Using conda from native finder: ${condaPath}`);
await state.set(CONDA_PATH_KEY, condaPath);
return condaPath;
}
}
}
}
throw new Error('Conda not found');
}
export async function getConda(native?: NativePythonFinder): Promise<string> {
const conda = getCondaPathSetting();
if (conda) {
traceInfo(`Using conda from settings: ${conda}`);
return conda;
}
return await getCondaExecutable(native);
}
async function _runConda(
conda: string,
args: string[],
log?: LogOutputChannel,
token?: CancellationToken,
): Promise<string> {
const deferred = createDeferred<string>();
args = quoteArgs(args);
const quotedConda = quoteStringIfNecessary(conda);
const timer = new StopWatch();
deferred.promise.finally(() => traceInfo(`Ran conda in ${timer.elapsedTime}: ${quotedConda} ${args.join(' ')}`));
const proc = spawnProcess(quotedConda, args, { shell: true });
token?.onCancellationRequested(() => {
proc.kill();
deferred.reject(new CancellationError());
});
proc.on('error', (err) => {
log?.error(`Error spawning conda: ${err}`);
deferred.reject(new Error(`Error spawning conda: ${err.message}`));
});
let stdout = '';
let stderr = '';
proc.stdout?.on('data', (data) => {
const d = data.toString('utf-8');
stdout += d;
log?.info(d.trim());
});
proc.stderr?.on('data', (data) => {
const d = data.toString('utf-8');
stderr += d;
log?.error(d.trim());
});
proc.on('close', () => {
deferred.resolve(stdout);
});
proc.on('exit', (code) => {
if (code !== 0) {
deferred.reject(new Error(`Failed to run "conda ${args.join(' ')}":\n ${stderr}`));
}
});
return deferred.promise;
}
async function runConda(args: string[], log?: LogOutputChannel, token?: CancellationToken): Promise<string> {
const conda = await getConda();
return await _runConda(conda, args, log, token);
}
export async function runCondaExecutable(
args: string[],
log?: LogOutputChannel,
token?: CancellationToken,
): Promise<string> {
const conda = await getCondaExecutable(undefined);
return await _runConda(conda, args, log, token);
}
interface CondaInfo {
envs_dirs: string[];
}
/**
* Runs `conda info --envs --json` and parses the result.
* Validates the JSON response structure at the parsing boundary.
* @returns Validated CondaInfo object
* @throws Error if conda command fails or returns invalid JSON structure
*/
async function getCondaInfo(): Promise<CondaInfo> {
const raw = await runConda(['info', '--envs', '--json']);
const parsed = JSON.parse(raw);
// Validate at the JSON→TypeScript boundary
if (!parsed || typeof parsed !== 'object') {
traceWarn(`conda info returned invalid data: ${typeof parsed}`);
throw new Error(`conda info returned invalid data type: ${typeof parsed}`);
}
const envsDirs = parsed['envs_dirs'];
if (envsDirs === undefined || envsDirs === null) {
traceWarn('conda info envs_dirs is undefined/null');
return { envs_dirs: [] };
}
if (!Array.isArray(envsDirs)) {
traceWarn(`conda info envs_dirs is not an array (type: ${typeof envsDirs})`);
return { envs_dirs: [] };
}
traceVerbose(`conda info returned ${envsDirs.length} environment directories`);
return { envs_dirs: envsDirs };
}
let prefixes: string[] | undefined;
export async function getPrefixes(): Promise<string[]> {
if (prefixes) {
return prefixes;
}
const state = await getWorkspacePersistentState();
const storedPrefixes = await state.get<string[]>(CONDA_PREFIXES_KEY);
if (storedPrefixes && Array.isArray(storedPrefixes)) {
prefixes = storedPrefixes;
return prefixes;
}
try {
const data = await getCondaInfo();
prefixes = data.envs_dirs;
await state.set(CONDA_PREFIXES_KEY, prefixes);
} catch (error) {
traceError('Failed to get conda environment prefixes', error);
prefixes = [];
}
return prefixes;
}
export async function getDefaultCondaPrefix(): Promise<string> {
const prefixes = await getPrefixes();
return prefixes.length > 0 ? prefixes[0] : path.join(os.homedir(), '.conda', 'envs');
}
export async function getVersion(root: string): Promise<string> {
const files = await fse.readdir(path.join(root, 'conda-meta'));
for (let file of files) {
if (file.startsWith('python-3') && file.endsWith('.json')) {
const content = fse.readJsonSync(path.join(root, 'conda-meta', file));
return content['version'] as string;
}
}
throw new Error('Python version not found');
}
/**
* Creates a PythonEnvironmentInfo object for a named conda environment.
* @param name The name of the conda environment
* @param prefix The installation prefix path for the environment
* @param executable The path to the Python executable
* @param version The Python version string
* @param conda The path to the conda executable (used for activation commands)
* @param envManager The environment manager instance
* @returns Promise resolving to a PythonEnvironmentInfo object
*/
export async function getNamedCondaPythonInfo(
name: string,
prefix: string,
executable: string,
version: string,
conda: string,
envManager: EnvironmentManager,
): Promise<PythonEnvironmentInfo> {
const { shellActivation, shellDeactivation } = await buildShellActivationMapForConda(prefix, envManager, name);
const sv = shortVersion(version);
return {
name: name,
environmentPath: Uri.file(prefix),
displayName: `${name} (${sv})`,
shortDisplayName: `${name}:${sv}`,
displayPath: prefix,
description: undefined,
tooltip: prefix,
version: version,
sysPrefix: prefix,
execInfo: {
run: { executable: path.join(executable) },
activatedRun: {
executable: path.join(executable),
args: [],
},
activation: [{ executable: conda, args: ['activate', name] }],
deactivation: [{ executable: conda, args: ['deactivate'] }],
shellActivation,
shellDeactivation,
},
group: name !== 'base' ? 'Named' : undefined,
};
}
/**
* Creates a PythonEnvironmentInfo object for a conda environment specified by prefix path.
* @param prefix The installation prefix path for the environment
* @param executable The path to the Python executable
* @param version The Python version string
* @param conda The path to the conda executable
* @param envManager The environment manager instance
* @returns Promise resolving to a PythonEnvironmentInfo object
*/
export async function getPrefixesCondaPythonInfo(
prefix: string,
executable: string,
version: string,
conda: string,
envManager: EnvironmentManager,
): Promise<PythonEnvironmentInfo> {
const sv = shortVersion(version);
const { shellActivation, shellDeactivation } = await buildShellActivationMapForConda(prefix, envManager);
const basename = path.basename(prefix);
return {
name: basename,
environmentPath: Uri.file(prefix),
displayName: `${basename} (${sv})`,
shortDisplayName: `${basename}:${sv}`,
displayPath: prefix,
description: undefined,
tooltip: prefix,
version: version,
sysPrefix: prefix,
execInfo: {
run: { executable: path.join(executable) },
activatedRun: {
executable: path.join(executable),
args: [],
},
activation: [{ executable: conda, args: ['activate', prefix] }],
deactivation: [{ executable: conda, args: ['deactivate'] }],
shellActivation,
shellDeactivation,
},
group: 'Prefix',
};
}
interface ShellCommandMaps {
shellActivation: Map<string, PythonCommandRunConfiguration[]>;
shellDeactivation: Map<string, PythonCommandRunConfiguration[]>;
}
/**
* Generates shell-specific activation and deactivation command maps for a conda environment.
* Creates appropriate activation/deactivation commands based on the environment type (named or prefix),
* platform (Windows/non-Windows), and available sourcing scripts.
*
* @param prefix The conda environment prefix path (installation location)
* @param envManager The conda environment manager instance
* @param name Optional name of the conda environment. If provided, used instead of prefix for activation
* @returns Promise resolving to shell-specific activation/deactivation command maps
*/
async function buildShellActivationMapForConda(
prefix: string,
envManager: EnvironmentManager,
name?: string,
): Promise<ShellCommandMaps> {
const logs: string[] = [];
let shellMaps: ShellCommandMaps;
try {
// Determine the environment identifier to use
const envIdentifier = name ? name : prefix;
logs.push(`Environment Configuration:
- Identifier: "${envIdentifier}"
- Prefix: "${prefix}"
- Name: "${name ?? 'undefined'}"
`);
let condaCommonActivate: PythonCommandRunConfiguration | undefined = {
executable: 'conda',
args: ['activate', envIdentifier],
};
let condaCommonDeactivate: PythonCommandRunConfiguration | undefined = {
executable: 'conda',
args: ['deactivate'],
};
if (!(envManager instanceof CondaEnvManager) || !envManager.sourcingInformation) {
logs.push('Error: Conda environment manager is not available, using default conda activation paths');
shellMaps = await generateShellActivationMapFromConfig([condaCommonActivate], [condaCommonDeactivate]);
return shellMaps;
}
const { isActiveOnLaunch, globalSourcingScript } = envManager.sourcingInformation;
// P1: first check to see if conda is already active in the whole VS Code workspace via sourcing info (set at startup)
if (isActiveOnLaunch) {
logs.push('✓ Conda already active on launch, using default activation commands');
shellMaps = await generateShellActivationMapFromConfig([condaCommonActivate], [condaCommonDeactivate]);
return shellMaps;
}
// get the local activation path, if exists use this
let localSourcingPath: string | undefined;
try {
localSourcingPath = await getLocalActivationScript(prefix);
} catch (err) {
logs.push(`Error getting local activation script: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
logs.push(`Local Activation:
- Status: ${localSourcingPath ? 'Found' : 'Not Found'}
- Path: ${localSourcingPath ?? 'N/A'}
`);
// Determine the preferred sourcing path with preference to local
const preferredSourcingPath = localSourcingPath || globalSourcingScript;
logs.push(`Preferred Sourcing:
- Selected Path: ${preferredSourcingPath ?? 'none found'}
- Source: ${localSourcingPath ? 'Local' : globalSourcingScript ? 'Global' : 'None'}
`);
// P2: Return shell activation if we have no sourcing
if (!preferredSourcingPath) {
logs.push('No sourcing path found, using default conda activation');
shellMaps = await generateShellActivationMapFromConfig([condaCommonActivate], [condaCommonDeactivate]);
return shellMaps;
}
// P3: Handle Windows specifically ;this is carryover from vscode-python
if (isWindows()) {
logs.push('✓ Using Windows-specific activation configuration');
// Get conda.sh for bash-based shells on Windows (e.g., Git Bash)
const condaShPath = envManager.sourcingInformation.shellSourcingScripts?.sh;
if (!condaShPath) {
logs.push('conda.sh not found, using preferred sourcing script path for bash activation');
}
shellMaps = await windowsExceptionGenerateConfig(
preferredSourcingPath,
envIdentifier,
envManager.sourcingInformation.condaFolder,
condaShPath,
);
return shellMaps;
}
logs.push('✓ Using shell-specific activation commands');
const condaShPath = envManager.sourcingInformation.shellSourcingScripts?.sh;
const condaFishPath = envManager.sourcingInformation.shellSourcingScripts?.fish;
const condaPs1Path = envManager.sourcingInformation.shellSourcingScripts?.ps1;
shellMaps = nonWindowsGenerateConfig(
preferredSourcingPath,
envIdentifier,
condaCommonDeactivate,
envManager.sourcingInformation.condaPath,
condaShPath,
condaFishPath,
condaPs1Path,
envManager.sourcingInformation.shellInitStatus,
);
return shellMaps;
} catch (error) {
logs.push(
`Error in shell activation map generation: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
// Fall back to default conda activation in case of error
shellMaps = await generateShellActivationMapFromConfig(
[{ executable: 'conda', args: ['activate', name || prefix] }],
[{ executable: 'conda', args: ['deactivate'] }],
);
return shellMaps;
} finally {
// Always print logs in a nicely formatted block, even if there was an error
traceInfo(
[
'=== Conda Shell Activation Map Generation ===',
...logs,
'==========================================',
].join('\n'),
);
}
}
async function generateShellActivationMapFromConfig(
activate: PythonCommandRunConfiguration[],
deactivate: PythonCommandRunConfiguration[],
): Promise<ShellCommandMaps> {
const shellActivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
const shellDeactivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
shellActivation.set(ShellConstants.GITBASH, activate);
shellDeactivation.set(ShellConstants.GITBASH, deactivate);
shellActivation.set(ShellConstants.CMD, activate);
shellDeactivation.set(ShellConstants.CMD, deactivate);
shellActivation.set(ShellConstants.BASH, activate);
shellDeactivation.set(ShellConstants.BASH, deactivate);
shellActivation.set(ShellConstants.SH, activate);
shellDeactivation.set(ShellConstants.SH, deactivate);
shellActivation.set(ShellConstants.ZSH, activate);
shellDeactivation.set(ShellConstants.ZSH, deactivate);
shellActivation.set(ShellConstants.PWSH, activate);
shellDeactivation.set(ShellConstants.PWSH, deactivate);
shellActivation.set(ShellConstants.FISH, activate);
shellDeactivation.set(ShellConstants.FISH, deactivate);
return { shellActivation, shellDeactivation };
}
/**
* Generates shell-specific activation configuration for Windows.
* Handles PowerShell, CMD, and Git Bash with appropriate scripts.
* @internal Exported for testing
*/
export async function windowsExceptionGenerateConfig(
sourceInitPath: string,
prefix: string,
condaFolder: string,
condaShPath?: string,
): Promise<ShellCommandMaps> {
const shellActivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
const shellDeactivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
const ps1Hook = await getCondaHookPs1Path(condaFolder);
traceVerbose(`PS1 hook path: ${ps1Hook ?? 'not found'}`);
const activation = ps1Hook ? ps1Hook : sourceInitPath;
// Quote the prefix path to handle spaces in paths (common on Windows)
const quotedPrefix = quoteStringIfNecessary(prefix);
const pwshActivate = [{ executable: activation }, { executable: 'conda', args: ['activate', quotedPrefix] }];
const cmdActivate = [{ executable: sourceInitPath }, { executable: 'conda', args: ['activate', quotedPrefix] }];
// When condaShPath is available, it is an initialization script (conda.sh) and does not
// itself activate an environment. In that case, first source conda.sh, then
// run "conda activate <envIdentifier>".
// When falling back to sourceInitPath, only emit a bash "source" command if the script
// is bash-compatible; on Windows, sourceInitPath may point to "activate.bat", which
// cannot be sourced by Git Bash, so in that case we skip emitting a Git Bash activation.
let bashActivate: PythonCommandRunConfiguration[];
if (condaShPath) {
bashActivate = [
{ executable: 'source', args: [condaShPath.replace(/\\/g, '/')] },
{ executable: 'conda', args: ['activate', quotedPrefix] },
];
} else if (sourceInitPath.toLowerCase().endsWith('.bat')) {
traceVerbose(
`Skipping Git Bash activation fallback because sourceInitPath is a batch script: ${sourceInitPath}`,
);
bashActivate = [];
} else {
bashActivate = [{ executable: 'source', args: [sourceInitPath.replace(/\\/g, '/'), quotedPrefix] }];
}
traceVerbose(
`Windows activation commands:
PowerShell: ${JSON.stringify(pwshActivate)},
CMD: ${JSON.stringify(cmdActivate)},
Bash: ${JSON.stringify(bashActivate)}`,
);
let condaCommonDeactivate: PythonCommandRunConfiguration | undefined = {
executable: 'conda',
args: ['deactivate'],
};
shellActivation.set(ShellConstants.GITBASH, bashActivate);
shellDeactivation.set(ShellConstants.GITBASH, [condaCommonDeactivate]);
shellActivation.set(ShellConstants.CMD, cmdActivate);
shellDeactivation.set(ShellConstants.CMD, [condaCommonDeactivate]);
shellActivation.set(ShellConstants.PWSH, pwshActivate);
shellDeactivation.set(ShellConstants.PWSH, [condaCommonDeactivate]);
return { shellActivation, shellDeactivation };
}
/**
* Generates shell-specific activation configuration for non-Windows (Linux/macOS).
* Uses conda.sh for bash-like shells, conda.fish for Fish, and conda-hook.ps1 for PowerShell.
* Falls back to `source <activate-script> <env>` for bash-like shells when conda.sh is unavailable.
*
* For each shell, when the shell-specific sourcing script is not found, checks whether
* `conda init <shell>` has been run (via shellInitStatus). If it has, bare `conda` is used
* since the shell will set up the conda function on startup. Otherwise, the full conda path
* is used as the executable.
*
* @internal Exported for testing
*/
export function nonWindowsGenerateConfig(
sourceInitPath: string,
envIdentifier: string,
condaCommonDeactivate: PythonCommandRunConfiguration,
condaPath: string,
condaShPath?: string,
condaFishPath?: string,
condaPs1Path?: string,
shellInitStatus?: ShellCondaInitStatus,
): ShellCommandMaps {
const shellActivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
const shellDeactivation: Map<string, PythonCommandRunConfiguration[]> = new Map();
const deactivate = [condaCommonDeactivate];
// Helper: determine the conda executable for a given shell based on init status.
// If `conda init <shell>` has been run, the shell profile sets up `conda` as a shell
// function on startup, so bare `conda` works. Otherwise, use the full path to the
// conda binary (the user will see an actionable error if hooks aren't set up).
const condaExe = (shell: keyof ShellCondaInitStatus): string => (shellInitStatus?.[shell] ? 'conda' : condaPath);
// Bash-like shells: use conda.sh if available, otherwise fall back to source activate
let bashActivate: PythonCommandRunConfiguration[];
if (condaShPath) {
bashActivate = [
{ executable: 'source', args: [condaShPath] },
{ executable: 'conda', args: ['activate', envIdentifier] },
];
} else {
bashActivate = [{ executable: 'source', args: [sourceInitPath, envIdentifier] }];
}
// POSIX sh (e.g. dash) does not support `source`; use `.` (dot) instead
let shActivate: PythonCommandRunConfiguration[];
if (condaShPath) {
shActivate = [
{ executable: '.', args: [condaShPath] },
{ executable: 'conda', args: ['activate', envIdentifier] },
];
} else {
shActivate = [{ executable: '.', args: [sourceInitPath, envIdentifier] }];
}
shellActivation.set(ShellConstants.BASH, bashActivate);
shellDeactivation.set(ShellConstants.BASH, deactivate);
shellActivation.set(ShellConstants.SH, shActivate);
shellDeactivation.set(ShellConstants.SH, deactivate);
shellActivation.set(ShellConstants.ZSH, bashActivate);
shellDeactivation.set(ShellConstants.ZSH, deactivate);
shellActivation.set(ShellConstants.GITBASH, bashActivate);
shellDeactivation.set(ShellConstants.GITBASH, deactivate);
// Fish shell: use conda.fish if available. Otherwise, check if `conda init fish`
// was run — if so, bare `conda` works; if not, use the full conda path.
let fishActivate: PythonCommandRunConfiguration[];
if (condaFishPath) {
fishActivate = [
{ executable: 'source', args: [condaFishPath] },
{ executable: 'conda', args: ['activate', envIdentifier] },
];
} else {
fishActivate = [{ executable: condaExe('fish'), args: ['activate', envIdentifier] }];
}
shellActivation.set(ShellConstants.FISH, fishActivate);
shellDeactivation.set(ShellConstants.FISH, deactivate);
// PowerShell: use conda-hook.ps1 if available. Otherwise, check if `conda init powershell`
// was run — if so, bare `conda` works; if not, use the full conda path.
let pwshActivate: PythonCommandRunConfiguration[];
if (condaPs1Path) {
pwshActivate = [
{ executable: '&', args: [condaPs1Path] },
{ executable: 'conda', args: ['activate', envIdentifier] },
];
} else {
pwshActivate = [{ executable: condaExe('pwsh'), args: ['activate', envIdentifier] }];
}
shellActivation.set(ShellConstants.PWSH, pwshActivate);
shellDeactivation.set(ShellConstants.PWSH, deactivate);
traceVerbose(
`Non-Windows activation commands:
Bash: ${JSON.stringify(bashActivate)},
SH: ${JSON.stringify(shActivate)},
Fish: ${JSON.stringify(fishActivate)},
PowerShell: ${JSON.stringify(pwshActivate)}`,
);
return { shellActivation, shellDeactivation };
}
function getCondaWithoutPython(name: string, prefix: string, conda: string): PythonEnvironmentInfo {
return {
name: name,
environmentPath: Uri.file(prefix),
displayName: `${name} (no-python)`,
shortDisplayName: `${name} (no-python)`,
displayPath: prefix,
description: prefix,
tooltip: l10n.t('Conda environment without Python'),
version: 'no-python',
sysPrefix: prefix,
iconPath: new ThemeIcon('stop'),
execInfo: {
run: { executable: conda },
},
group: name.length > 0 ? 'Named' : 'Prefix',
};
}
async function nativeToPythonEnv(
e: NativeEnvInfo,
api: PythonEnvironmentApi,
manager: EnvironmentManager,
log: LogOutputChannel,
conda: string,
): Promise<PythonEnvironment | undefined> {
// Defensive check: Validate NativeEnvInfo object
if (!e) {
traceWarn('nativeToPythonEnv received null/undefined NativeEnvInfo');
return undefined;
}
if (!(e.prefix && e.executable && e.version)) {
let name = e.name;
const environment = api.createPythonEnvironmentItem(
getCondaWithoutPython(name ?? '', e.prefix ?? '', conda),
manager,
);
log.info(`Found a No-Python conda environment: ${e.executable ?? e.prefix ?? 'conda-no-python'}`);
return environment;
}
if (e.name === 'base') {
const environment = api.createPythonEnvironmentItem(
await getNamedCondaPythonInfo('base', e.prefix, e.executable, e.version, conda, manager),
manager,
);
log.info(`Found base environment: ${e.prefix}`);
return environment;
} else if (e.name) {
// Server explicitly provided a name - this is a named environment (created with -n/--name)
// Use name-based activation: conda activate <name>
const environment = api.createPythonEnvironmentItem(
await getNamedCondaPythonInfo(e.name, e.prefix, e.executable, e.version, conda, manager),
manager,
);
log.info(`Found named environment: ${e.name} at ${e.prefix}`);
return environment;
} else {
// Server returned undefined/null name - this is a prefix-based environment (created with -p/--prefix)
// Use prefix-based activation: conda activate <full-path>
// This aligns with the PR #331 fix in python-environment-tools
const environment = api.createPythonEnvironmentItem(
await getPrefixesCondaPythonInfo(e.prefix, e.executable, e.version, conda, manager),
manager,
);
log.info(`Found prefix environment: ${e.prefix}`);
return environment;
}
}
export async function resolveCondaPath(
fsPath: string,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
log: LogOutputChannel,
manager: EnvironmentManager,
): Promise<PythonEnvironment | undefined> {
try {
const e = await nativeFinder.resolve(fsPath);
if (e.kind !== NativePythonEnvironmentKind.conda) {
return undefined;
}
const conda = await getConda();
return nativeToPythonEnv(e, api, manager, log, conda);
} catch {
return undefined;
}
}
export async function refreshCondaEnvs(
hardRefresh: boolean,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
log: LogOutputChannel,
manager: EnvironmentManager,
): Promise<PythonEnvironment[]> {
log.info(`Refreshing conda environments (hardRefresh=${hardRefresh})`);
let data: (NativeEnvInfo | NativeEnvManagerInfo)[];
try {
data = await nativeFinder.refresh(hardRefresh);
} catch (error) {
traceError('Failed to refresh native finder for conda environments', error);
log.error(`Failed to refresh native finder: ${error instanceof Error ? error.message : String(error)}`);
return [];
}
// Ensure data is a valid array before proceeding
if (!data || !Array.isArray(data)) {
traceWarn(`Native finder returned invalid data: ${typeof data}, expected array`);
log.warn(`Native finder returned invalid data type: ${typeof data}`);
return [];
}
traceVerbose(`Native finder returned ${data.length} items for conda refresh`);
let conda: string | undefined = undefined;
try {
conda = await getConda();
} catch (error) {
traceVerbose(`getConda() failed, will try to find conda from native data: ${error}`);
conda = undefined;
}
if (conda === undefined) {
const managers = data
.filter((e) => !isNativeEnvInfo(e))
.map((e) => e as NativeEnvManagerInfo)
.filter((e) => e.tool.toLowerCase() === 'conda');
if (managers.length === 0) {
traceWarn('No conda manager found in native finder data');
log.warn('No conda manager found in native finder data');
return [];
}
conda = managers[0].executable;
await setConda(conda);
}
const condaPath = conda;
if (condaPath) {
const envs = data
.filter((e) => isNativeEnvInfo(e))
.map((e) => e as NativeEnvInfo)
.filter((e) => e.kind === NativePythonEnvironmentKind.conda);
const collection: PythonEnvironment[] = [];
await Promise.all(
envs.map(async (e) => {
try {
const environment = await nativeToPythonEnv(e, api, manager, log, condaPath);
if (environment) {
collection.push(environment);
}
} catch (error) {
traceError(
`Failed to convert native env to Python environment: ${e.prefix ?? e.executable}`,
error,
);
log.error(
`Failed to process conda environment ${e.prefix ?? e.executable}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}),
);
return sortEnvironments(collection);
}
log.error('Conda not found');
return [];
}
export function getName(api: PythonEnvironmentApi, uris?: Uri | Uri[]): string | undefined {
if (!uris) {
return undefined;
}
if (Array.isArray(uris) && uris.length !== 1) {
return undefined;
}
return api.getPythonProject(Array.isArray(uris) ? uris[0] : uris)?.name;
}
export async function getLocation(api: PythonEnvironmentApi, uris: Uri | Uri[]): Promise<string | undefined> {
if (!uris || (Array.isArray(uris) && (uris.length === 0 || uris.length > 1))) {
const projects: PythonProject[] = [];
if (Array.isArray(uris)) {
for (let uri of uris) {
const project = api.getPythonProject(uri);
if (project && !projects.includes(project)) {
projects.push(project);
}
}
} else {
api.getPythonProjects().forEach((p) => projects.push(p));
}
const project = await pickProject(projects);
return project?.uri.fsPath;
}
return api.getPythonProject(Array.isArray(uris) ? uris[0] : uris)?.uri.fsPath;
}
const RECOMMENDED_CONDA_PYTHON = '3.11.11';
export function trimVersionToMajorMinor(version: string): string {
const match = version.match(/^(\d+\.\d+\.\d+)/);
return match ? match[1] : version;
}
export async function pickPythonVersion(
api: PythonEnvironmentApi,
token?: CancellationToken,
): Promise<string | undefined> {
const envs = await api.getEnvironments('global');
let versions = Array.from(
new Set(
envs
.map((env) => env.version)
.filter(Boolean)
.map((v) => trimVersionToMajorMinor(v)), // cut to 3 digits
),
);
// Sort versions by major version (descending), ignoring minor/patch for simplicity
const parseMajorMinor = (v: string) => {
const m = v.match(/^(\d+)(?:\.(\d+))?/);
return { major: m ? Number(m[1]) : 0, minor: m && m[2] ? Number(m[2]) : 0 };
};
versions = versions.sort((a, b) => {