Skip to content

Commit 38bd529

Browse files
committed
bug: fix gitignore add for more scenarios (microsoft#627)
fixes microsoft#619 since environmentPath for an environment can be "Path to the python binary or environment folder." need to update code to support if the path is directly to a python binary. If so get the parent, parent of the binary to get the venv folder
1 parent 174650e commit 38bd529

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

src/managers/builtin/venvManager.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
} from '../../api';
3131
import { PYTHON_EXTENSION_ID } from '../../common/constants';
3232
import { VenvManagerStrings } from '../../common/localize';
33-
import { traceError } from '../../common/logging';
33+
import { traceError, traceWarn } from '../../common/logging';
3434
import { createDeferred, Deferred } from '../../common/utils/deferred';
3535
import { showErrorMessage, withProgress } from '../../common/window.apis';
3636
import { findParentIfFile } from '../../features/envCommands';
@@ -186,12 +186,30 @@ export class VenvManager implements EnvironmentManager {
186186

187187
// Add .gitignore to the .venv folder
188188
try {
189-
const venvDir = environment.environmentPath.fsPath;
190-
const gitignorePath = path.join(venvDir, '.gitignore');
189+
// determine if env path is python binary or environment folder
190+
let envPath = environment.environmentPath.fsPath;
191+
try {
192+
const stat = await fs.stat(envPath);
193+
if (!stat.isDirectory()) {
194+
// If the env path is a file (likely the python binary), use parent-parent as the env path
195+
// following format of .venv/bin/python or .venv\Scripts\python.exe
196+
envPath = Uri.file(path.dirname(path.dirname(envPath))).fsPath;
197+
}
198+
} catch (err) {
199+
// If stat fails, fallback to original envPath
200+
traceWarn(
201+
`Failed to stat environment path: ${envPath}. Error: ${
202+
err instanceof Error ? err.message : String(err)
203+
}, continuing to attempt to create .gitignore.`,
204+
);
205+
}
206+
const gitignorePath = path.join(envPath, '.gitignore');
191207
await fs.writeFile(gitignorePath, '*\n', { flag: 'w' });
192208
} catch (err) {
193209
traceError(
194-
`Failed to create .gitignore in venv: ${err instanceof Error ? err.message : String(err)}`,
210+
`Failed to create .gitignore in venv: ${
211+
err instanceof Error ? err.message : String(err)
212+
}, continuing.`,
195213
);
196214
}
197215

0 commit comments

Comments
 (0)