|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +import * as fse from 'fs-extra'; |
| 5 | +import * as path from 'path'; |
| 6 | +import { |
| 7 | + Disposable, |
| 8 | + EnvironmentVariableScope, |
| 9 | + GlobalEnvironmentVariableCollection, |
| 10 | + workspace, |
| 11 | + WorkspaceFolder, |
| 12 | +} from 'vscode'; |
| 13 | +import { traceError, traceVerbose } from '../../common/logging'; |
| 14 | +import { resolveVariables } from '../../common/utils/internalVariables'; |
| 15 | +import { getConfiguration, getWorkspaceFolder } from '../../common/workspace.apis'; |
| 16 | +import { EnvVarManager } from '../execution/envVariableManager'; |
| 17 | + |
| 18 | +/** |
| 19 | + * Manages injection of workspace-specific environment variables into VS Code terminals |
| 20 | + * using the GlobalEnvironmentVariableCollection API. |
| 21 | + */ |
| 22 | +export class TerminalEnvVarInjector implements Disposable { |
| 23 | + private disposables: Disposable[] = []; |
| 24 | + |
| 25 | + constructor( |
| 26 | + private readonly envVarCollection: GlobalEnvironmentVariableCollection, |
| 27 | + private readonly envVarManager: EnvVarManager, |
| 28 | + ) { |
| 29 | + this.initialize(); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Initialize the injector by setting up watchers and injecting initial environment variables. |
| 34 | + */ |
| 35 | + private async initialize(): Promise<void> { |
| 36 | + traceVerbose('TerminalEnvVarInjector: Initializing environment variable injection'); |
| 37 | + |
| 38 | + // Listen for environment variable changes from the manager |
| 39 | + this.disposables.push( |
| 40 | + this.envVarManager.onDidChangeEnvironmentVariables((args) => { |
| 41 | + if (!args.uri) { |
| 42 | + // No specific URI, reload all workspaces |
| 43 | + this.updateEnvironmentVariables().catch((error) => { |
| 44 | + traceError('Failed to update environment variables:', error); |
| 45 | + }); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + const affectedWorkspace = getWorkspaceFolder(args.uri); |
| 50 | + if (!affectedWorkspace) { |
| 51 | + // No workspace folder found for this URI, reloading all workspaces |
| 52 | + this.updateEnvironmentVariables().catch((error) => { |
| 53 | + traceError('Failed to update environment variables:', error); |
| 54 | + }); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + if (args.changeType === 2) { |
| 59 | + // FileChangeType.Deleted |
| 60 | + this.clearWorkspaceVariables(affectedWorkspace); |
| 61 | + } else { |
| 62 | + this.updateEnvironmentVariables(affectedWorkspace).catch((error) => { |
| 63 | + traceError('Failed to update environment variables:', error); |
| 64 | + }); |
| 65 | + } |
| 66 | + }), |
| 67 | + ); |
| 68 | + |
| 69 | + // Initial load of environment variables |
| 70 | + await this.updateEnvironmentVariables(); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Update environment variables in the terminal collection. |
| 75 | + */ |
| 76 | + private async updateEnvironmentVariables(workspaceFolder?: WorkspaceFolder): Promise<void> { |
| 77 | + try { |
| 78 | + if (workspaceFolder) { |
| 79 | + // Update only the specified workspace |
| 80 | + traceVerbose( |
| 81 | + `TerminalEnvVarInjector: Updating environment variables for workspace: ${workspaceFolder.uri.fsPath}`, |
| 82 | + ); |
| 83 | + await this.injectEnvironmentVariablesForWorkspace(workspaceFolder); |
| 84 | + } else { |
| 85 | + // No provided workspace - update all workspaces |
| 86 | + this.envVarCollection.clear(); |
| 87 | + |
| 88 | + const workspaceFolders = workspace.workspaceFolders; |
| 89 | + if (!workspaceFolders || workspaceFolders.length === 0) { |
| 90 | + traceVerbose('TerminalEnvVarInjector: No workspace folders found, skipping env var injection'); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + traceVerbose('TerminalEnvVarInjector: Updating environment variables for all workspaces'); |
| 95 | + for (const folder of workspaceFolders) { |
| 96 | + await this.injectEnvironmentVariablesForWorkspace(folder); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + traceVerbose('TerminalEnvVarInjector: Environment variable injection completed'); |
| 101 | + } catch (error) { |
| 102 | + traceError('TerminalEnvVarInjector: Error updating environment variables:', error); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Inject environment variables for a specific workspace. |
| 108 | + */ |
| 109 | + private async injectEnvironmentVariablesForWorkspace(workspaceFolder: WorkspaceFolder): Promise<void> { |
| 110 | + const workspaceUri = workspaceFolder.uri; |
| 111 | + try { |
| 112 | + const envVars = await this.envVarManager.getEnvironmentVariables(workspaceUri); |
| 113 | + |
| 114 | + // use scoped environment variable collection |
| 115 | + const envVarScope = this.getEnvironmentVariableCollectionScoped({ workspaceFolder }); |
| 116 | + envVarScope.clear(); // Clear existing variables for this workspace |
| 117 | + |
| 118 | + // Track which .env file is being used for logging |
| 119 | + const config = getConfiguration('python', workspaceUri); |
| 120 | + const envFilePath = config.get<string>('envFile'); |
| 121 | + const resolvedEnvFilePath: string | undefined = envFilePath |
| 122 | + ? path.resolve(resolveVariables(envFilePath, workspaceUri)) |
| 123 | + : undefined; |
| 124 | + const defaultEnvFilePath: string = path.join(workspaceUri.fsPath, '.env'); |
| 125 | + |
| 126 | + let activeEnvFilePath: string = resolvedEnvFilePath || defaultEnvFilePath; |
| 127 | + if (activeEnvFilePath && (await fse.pathExists(activeEnvFilePath))) { |
| 128 | + traceVerbose(`TerminalEnvVarInjector: Using env file: ${activeEnvFilePath}`); |
| 129 | + } else { |
| 130 | + traceVerbose( |
| 131 | + `TerminalEnvVarInjector: No .env file found for workspace: ${workspaceUri.fsPath}, not injecting environment variables.`, |
| 132 | + ); |
| 133 | + return; // No .env file to inject |
| 134 | + } |
| 135 | + |
| 136 | + for (const [key, value] of Object.entries(envVars)) { |
| 137 | + if (value === undefined) { |
| 138 | + // Remove the environment variable if the value is undefined |
| 139 | + envVarScope.delete(key); |
| 140 | + } else { |
| 141 | + envVarScope.replace(key, value); |
| 142 | + } |
| 143 | + } |
| 144 | + } catch (error) { |
| 145 | + traceError( |
| 146 | + `TerminalEnvVarInjector: Error injecting environment variables for workspace ${workspaceUri.fsPath}:`, |
| 147 | + error, |
| 148 | + ); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Dispose of the injector and clean up resources. |
| 154 | + */ |
| 155 | + dispose(): void { |
| 156 | + traceVerbose('TerminalEnvVarInjector: Disposing'); |
| 157 | + this.disposables.forEach((disposable) => disposable.dispose()); |
| 158 | + this.disposables = []; |
| 159 | + |
| 160 | + // Clear all environment variables from the collection |
| 161 | + this.envVarCollection.clear(); |
| 162 | + } |
| 163 | + |
| 164 | + private getEnvironmentVariableCollectionScoped(scope: EnvironmentVariableScope = {}) { |
| 165 | + const envVarCollection = this.envVarCollection as GlobalEnvironmentVariableCollection; |
| 166 | + return envVarCollection.getScoped(scope); |
| 167 | + } |
| 168 | + |
| 169 | + /** |
| 170 | + * Clear all environment variables for a workspace. |
| 171 | + */ |
| 172 | + private clearWorkspaceVariables(workspaceFolder: WorkspaceFolder): void { |
| 173 | + try { |
| 174 | + const scope = this.getEnvironmentVariableCollectionScoped({ workspaceFolder }); |
| 175 | + scope.clear(); |
| 176 | + } catch (error) { |
| 177 | + traceError(`Failed to clear environment variables for workspace ${workspaceFolder.uri.fsPath}:`, error); |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments