From 9a856ff5979e6db81a49a4481fa55c01955e43f7 Mon Sep 17 00:00:00 2001 From: Arnab Chatterjee Date: Sat, 28 Nov 2026 14:06:25 +0530 Subject: [PATCH 1/2] Merge env keys that differ only in case on Windows On Windows the debug env can end up with both "Path" and "PATH", which debugpy rejects with 'Found duplicate in "env": PATH'. Normalize such keys before handing the configuration to the debug adapter, merging the distinct PATH entries. Refs #261 Co-Authored-By: Claude Sonnet 5.5 --- .../configuration/resolvers/helper.ts | 44 ++++++++++++++++++- .../resolvers/helper.unit.test.ts | 27 +++++++++++- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/extension/debugger/configuration/resolvers/helper.ts b/src/extension/debugger/configuration/resolvers/helper.ts index 6791bded..e26902f1 100644 --- a/src/extension/debugger/configuration/resolvers/helper.ts +++ b/src/extension/debugger/configuration/resolvers/helper.ts @@ -5,12 +5,54 @@ '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 + * into one entry. For the executable search path the distinct entries of all variants are + * merged; for any other variable the last value wins. + */ +export function normalizeEnvironmentVariableCase( + env: EnvironmentVariables, + ostype: OSType = getOSType(), +): EnvironmentVariables { + if (ostype !== OSType.Windows) { + return env; + } + const preferredPathName = getSearchPathEnvVarNames(ostype)[0]; + const firstKeyByUpper = new Map(); + const result: EnvironmentVariables = {}; + for (const key of Object.keys(env)) { + const upper = key.toUpperCase(); + const existingKey = firstKeyByUpper.get(upper); + if (existingKey === undefined) { + firstKeyByUpper.set(upper, key); + result[key] = env[key]; + continue; + } + const previous = result[existingKey]; + const current = env[key]; + let merged = current; + if (upper === 'PATH' && typeof previous === 'string' && typeof current === 'string') { + const entries = [...previous.split(';'), ...current.split(';')].filter( + (entry, index, all) => entry.length > 0 && all.indexOf(entry) === index, + ); + merged = entries.join(';'); + } + delete result[existingKey]; + const finalKey = upper === 'PATH' ? preferredPathName : key; + firstKeyByUpper.set(upper, finalKey); + result[finalKey] = merged; + } + return result; +} + export async function getDebugEnvironmentVariables(args: LaunchRequestArguments): Promise { const pathVariableName = getSearchPathEnvVarNames()[0]; @@ -67,7 +109,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..cd71b22c 100644 --- a/src/test/unittest/configuration/resolvers/helper.unit.test.ts +++ b/src/test/unittest/configuration/resolvers/helper.unit.test.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/naming-convention */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -9,7 +10,11 @@ import * as typemoq from 'typemoq'; import { TextDocument, TextEditor } from 'vscode'; import { PYTHON_LANGUAGE } from '../../../../extension/common/constants'; import * as vscodeapi from '../../../../extension/common/vscodeapi'; -import { getProgram } from '../../../../extension/debugger/configuration/resolvers/helper'; +import { OSType } from '../../../../extension/common/platform'; +import { + getProgram, + normalizeEnvironmentVariableCase, +} from '../../../../extension/debugger/configuration/resolvers/helper'; suite('Debugging - Helpers', () => { let getActiveTextEditorStub: sinon.SinonStub; @@ -67,4 +72,24 @@ 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('Leaves env untouched on non-Windows platforms', () => { + const env = { Path: 'a', PATH: 'b' }; + expect(normalizeEnvironmentVariableCase(env, OSType.Linux)).to.deep.equal(env); + }); + }); }); From 77e0b0f4cb3f9693770b7aeb3a0f16b4bffa5ed3 Mon Sep 17 00:00:00 2001 From: Arnab Chatterjee Date: Sat, 28 Nov 2026 14:13:51 +0530 Subject: [PATCH 2/2] Preserve env source precedence when merging case variants on Windows Address review feedback: instead of collapsing case-colliding keys at the end, canonicalize each env source (launch env, env file) first and make mergeVariables case-insensitive on Windows. This keeps launch > env file > system precedence for ordinary variables, and keeps user-supplied PATH entries ahead of the system PATH. Adds getDebugEnvironmentVariables regression tests for both cases. Co-Authored-By: Claude Sonnet 5.5 --- src/extension/common/variables/environment.ts | 24 +++++++- .../configuration/resolvers/helper.ts | 43 +++++++------- .../resolvers/helper.unit.test.ts | 58 +++++++++++++++++++ 3 files changed, 102 insertions(+), 23 deletions(-) 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 e26902f1..baf65daf 100644 --- a/src/extension/debugger/configuration/resolvers/helper.ts +++ b/src/extension/debugger/configuration/resolvers/helper.ts @@ -15,8 +15,9 @@ 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 - * into one entry. For the executable search path the distinct entries of all variants are - * merged; for any other variable the last value wins. + * 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, @@ -25,30 +26,31 @@ export function normalizeEnvironmentVariableCase( if (ostype !== OSType.Windows) { return env; } - const preferredPathName = getSearchPathEnvVarNames(ostype)[0]; - const firstKeyByUpper = new Map(); + const canonicalPathName = getSearchPathEnvVarNames(ostype)[0]; + const keyByUpper = new Map(); const result: EnvironmentVariables = {}; for (const key of Object.keys(env)) { const upper = key.toUpperCase(); - const existingKey = firstKeyByUpper.get(upper); + const isPath = upper === canonicalPathName.toUpperCase(); + const finalKey = isPath ? canonicalPathName : key; + const existingKey = keyByUpper.get(upper); + const current = env[key]; if (existingKey === undefined) { - firstKeyByUpper.set(upper, key); - result[key] = env[key]; + keyByUpper.set(upper, finalKey); + result[finalKey] = current; continue; } const previous = result[existingKey]; - const current = env[key]; - let merged = current; - if (upper === 'PATH' && typeof previous === 'string' && typeof current === 'string') { + 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, ); - merged = entries.join(';'); + result[finalKey] = entries.join(';'); + } else { + result[finalKey] = current; } - delete result[existingKey]; - const finalKey = upper === 'PATH' ? preferredPathName : key; - firstKeyByUpper.set(upper, finalKey); - result[finalKey] = merged; } return result; } @@ -57,12 +59,13 @@ export async function getDebugEnvironmentVariables(args: LaunchRequestArguments) 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. diff --git a/src/test/unittest/configuration/resolvers/helper.unit.test.ts b/src/test/unittest/configuration/resolvers/helper.unit.test.ts index cd71b22c..5fdcf28d 100644 --- a/src/test/unittest/configuration/resolvers/helper.unit.test.ts +++ b/src/test/unittest/configuration/resolvers/helper.unit.test.ts @@ -5,13 +5,17 @@ '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 { OSType } from '../../../../extension/common/platform'; import { + getDebugEnvironmentVariables, getProgram, normalizeEnvironmentVariableCase, } from '../../../../extension/debugger/configuration/resolvers/helper'; @@ -87,9 +91,63 @@ suite('Debugging - Helpers', () => { 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']); + }); + }); });