diff --git a/src/extension/common/variables/environment.ts b/src/extension/common/variables/environment.ts index ce67bb8b..ac3e1b2c 100644 --- a/src/extension/common/variables/environment.ts +++ b/src/extension/common/variables/environment.ts @@ -6,6 +6,7 @@ import * as path from 'path'; import { sendTelemetryEvent } from '../../telemetry'; import { EventName } from '../../telemetry/constants'; import { traceError } from '../log/logging'; +import { getOSType, OSType } from '../platform'; import { getSearchPathEnvVarNames } from '../utils/exec'; import { EnvironmentVariables } from './types'; @@ -46,17 +47,34 @@ export function mergeVariables( source: EnvironmentVariables, target: EnvironmentVariables, options?: { overwrite?: boolean }, + ostype: OSType = getOSType(), ) { if (!target) { return; } - const settingsNotToMerge = ['PYTHONPATH', getSearchPathEnvVarNames()[0]]; + // Variable names are case-insensitive on Windows, so match them that way there. Otherwise + // "foo" and "FOO" would both end up in the target and be rejected by debugpy. + const caseInsensitive = ostype === OSType.Windows; + const normalize = (name: string) => (caseInsensitive ? name.toUpperCase() : name); + const settingsNotToMerge = ['PYTHONPATH', getSearchPathEnvVarNames(ostype)[0]].map(normalize); + const targetKeys = new Map(); + Object.keys(target).forEach((key) => targetKeys.set(normalize(key), key)); + Object.keys(source).forEach((setting) => { - if (settingsNotToMerge.indexOf(setting) >= 0) { + const normalized = normalize(setting); + if (settingsNotToMerge.indexOf(normalized) >= 0) { return; } - if (target[setting] === undefined || options?.overwrite) { + const existingKey = targetKeys.get(normalized); + if (existingKey === undefined || target[existingKey] === undefined) { + target[setting] = source[setting]; + targetKeys.set(normalized, setting); + } else if (options?.overwrite) { + if (existingKey !== setting) { + delete target[existingKey]; + } target[setting] = source[setting]; + targetKeys.set(normalized, setting); } }); } diff --git a/src/extension/debugger/configuration/resolvers/helper.ts b/src/extension/debugger/configuration/resolvers/helper.ts index 6791bded..baf65daf 100644 --- a/src/extension/debugger/configuration/resolvers/helper.ts +++ b/src/extension/debugger/configuration/resolvers/helper.ts @@ -5,22 +5,67 @@ 'use strict'; import { PYTHON_LANGUAGE } from '../../../common/constants'; +import { getOSType, OSType } from '../../../common/platform'; import { getSearchPathEnvVarNames } from '../../../common/utils/exec'; import { EnvironmentVariables } from '../../../common/variables/types'; import { getActiveTextEditor } from '../../../common/vscodeapi'; import { LaunchRequestArguments } from '../../../types'; import * as envParser from '../../../common/variables/environment'; +/** + * Environment variable names are case-insensitive on Windows, but debugpy rejects an "env" + * that contains keys differing only in case (e.g. both "Path" and "PATH"). Collapse such keys + * within a single source into one entry. All spellings of the executable search path are + * renamed to the canonical one and their distinct entries merged in order; for any other + * variable the last value wins. + */ +export function normalizeEnvironmentVariableCase( + env: EnvironmentVariables, + ostype: OSType = getOSType(), +): EnvironmentVariables { + if (ostype !== OSType.Windows) { + return env; + } + const canonicalPathName = getSearchPathEnvVarNames(ostype)[0]; + const keyByUpper = new Map(); + const result: EnvironmentVariables = {}; + for (const key of Object.keys(env)) { + const upper = key.toUpperCase(); + const isPath = upper === canonicalPathName.toUpperCase(); + const finalKey = isPath ? canonicalPathName : key; + const existingKey = keyByUpper.get(upper); + const current = env[key]; + if (existingKey === undefined) { + keyByUpper.set(upper, finalKey); + result[finalKey] = current; + continue; + } + const previous = result[existingKey]; + delete result[existingKey]; + keyByUpper.set(upper, finalKey); + if (isPath && typeof previous === 'string' && typeof current === 'string') { + const entries = [...previous.split(';'), ...current.split(';')].filter( + (entry, index, all) => entry.length > 0 && all.indexOf(entry) === index, + ); + result[finalKey] = entries.join(';'); + } else { + result[finalKey] = current; + } + } + return result; +} + export async function getDebugEnvironmentVariables(args: LaunchRequestArguments): Promise { const pathVariableName = getSearchPathEnvVarNames()[0]; // Merge variables from both .env file and env json variables. - const debugLaunchEnvVars: Record = - args.env && Object.keys(args.env).length > 0 - ? ({ ...args.env } as Record) - : ({} as Record); + // On Windows, names that differ only in case (e.g. "PATH" vs "Path") are the same variable, so + // canonicalize each source before combining them to keep launch > env file > system precedence. + const debugLaunchEnvVars = normalizeEnvironmentVariableCase( + args.env && Object.keys(args.env).length > 0 ? { ...args.env } : {}, + ) as Record; const envFileVars = await envParser.parseFile(args.envFile, debugLaunchEnvVars); - const env = envFileVars ? { ...envFileVars } : {}; + const env = envFileVars ? normalizeEnvironmentVariableCase({ ...envFileVars }) : {}; // "overwrite: true" to ensure that debug-configuration env variable values // take precedence over env file. @@ -67,7 +112,7 @@ export async function getDebugEnvironmentVariables(args: LaunchRequestArguments) env.GEVENT_SUPPORT = 'True'; // this is read in pydevd_constants.py } - return env; + return normalizeEnvironmentVariableCase(env); } export function getProgram(): string | undefined { diff --git a/src/test/unittest/configuration/resolvers/helper.unit.test.ts b/src/test/unittest/configuration/resolvers/helper.unit.test.ts index c2d6d483..5fdcf28d 100644 --- a/src/test/unittest/configuration/resolvers/helper.unit.test.ts +++ b/src/test/unittest/configuration/resolvers/helper.unit.test.ts @@ -1,15 +1,24 @@ +/* eslint-disable @typescript-eslint/naming-convention */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. 'use strict'; import { expect } from 'chai'; +import * as path from 'path'; import * as sinon from 'sinon'; import * as typemoq from 'typemoq'; import { TextDocument, TextEditor } from 'vscode'; import { PYTHON_LANGUAGE } from '../../../../extension/common/constants'; +import * as platform from '../../../../extension/common/platform'; +import * as envParser from '../../../../extension/common/variables/environment'; import * as vscodeapi from '../../../../extension/common/vscodeapi'; -import { getProgram } from '../../../../extension/debugger/configuration/resolvers/helper'; +import { OSType } from '../../../../extension/common/platform'; +import { + getDebugEnvironmentVariables, + getProgram, + normalizeEnvironmentVariableCase, +} from '../../../../extension/debugger/configuration/resolvers/helper'; suite('Debugging - Helpers', () => { let getActiveTextEditorStub: sinon.SinonStub; @@ -67,4 +76,78 @@ suite('Debugging - Helpers', () => { expect(program).to.be.equal(undefined, 'Not undefined'); }); + + suite('normalizeEnvironmentVariableCase', () => { + test('Merges "Path" and "PATH" into a single entry on Windows', () => { + const result = normalizeEnvironmentVariableCase( + { Path: 'C:a;C:\b', PATH: 'C:\b;C:c', FOO: '1' }, + OSType.Windows, + ); + expect(result).to.deep.equal({ Path: 'C:a;C:\b;C:c', FOO: '1' }); + }); + + test('Last value wins for other variables differing only in case on Windows', () => { + const result = normalizeEnvironmentVariableCase({ Foo: '1', FOO: '2' }, OSType.Windows); + expect(result).to.deep.equal({ FOO: '2' }); + }); + + test('Renames a lone "PATH" to the canonical "Path" on Windows', () => { + const result = normalizeEnvironmentVariableCase({ PATH: 'C:a' }, OSType.Windows); + expect(result).to.deep.equal({ Path: 'C:a' }); + }); + + test('Leaves env untouched on non-Windows platforms', () => { + const env = { Path: 'a', PATH: 'b' }; + expect(normalizeEnvironmentVariableCase(env, OSType.Linux)).to.deep.equal(env); + }); + }); + + suite('getDebugEnvironmentVariables on Windows', () => { + const delimiter = path.delimiter; + let processEnvStub: sinon.SinonStub; + + function setup_(systemEnv: Record, envFileVars?: Record) { + sinon.stub(platform, 'getOSType').returns(OSType.Windows); + processEnvStub = sinon.stub(process, 'env').value(systemEnv); + sinon.stub(envParser, 'parseFile').resolves(envFileVars); + } + + teardown(() => { + processEnvStub?.restore(); + }); + + test('Launch env value wins over inherited variable differing only in case', async () => { + setup_({ FOO: 'system', Path: 'C:system' }); + + const env = await getDebugEnvironmentVariables({ + env: { foo: 'launch' }, + console: 'internalConsole', + } as any); + + expect(env.foo).to.equal('launch'); + expect(Object.keys(env).filter((k) => k.toUpperCase() === 'FOO')).to.deep.equal(['foo']); + }); + + test('Launch variable wins over env file variable differing only in case', async () => { + setup_({ Path: 'C:system' }, { Foo: 'file' }); + + const env = await getDebugEnvironmentVariables({ env: { FOO: 'launch' }, envFile: 'x.env' } as any); + + expect(env.FOO).to.equal('launch'); + expect(Object.keys(env).filter((k) => k.toUpperCase() === 'FOO')).to.have.length(1); + }); + + test('Launch PATH entries come before the system PATH and no duplicate key remains', async () => { + setup_({ Path: 'C:system' }, { Path: 'C:\file' }); + + const env = await getDebugEnvironmentVariables({ + env: { PATH: 'C:launch' }, + envFile: 'x.env', + console: 'internalConsole', + } as any); + + expect(env.Path).to.equal(['C:\file', 'C:launch', 'C:system'].join(delimiter)); + expect(Object.keys(env).filter((k) => k.toUpperCase() === 'PATH')).to.deep.equal(['Path']); + }); + }); });