import * as fse from 'fs-extra' ; import * as path from 'path' ; import * as vscode from 'vscode' ; import { pythonVenvSetting } from "../constants" ; import { ext } from '../extensionVariables' ; import { getWorkspaceSetting } from '../vsCodeConfig/settings' ; import { cpUtils } from './cpUtils' ; export namespace venvUtils { enum Terminal { bash , cmd , powerShell } export function convertToVenvCommand ( command , folderPath ) { const terminal = getTerminal ( process . platform ) ; const venvName = getWorkspaceSetting < string > ( pythonVenvSetting , folderPath ) ; if ( venvName ) { return joinCommands ( terminal , getVenvActivateCommand ( venvName , terminal , process . platform ) , command ) ; } else { return command ; } } export function convertToVenvPythonCommand ( command , venvName , platform ) { const terminal = getTerminal ( platform ) ; const pythonPath = getVenvPath ( venvName , 'python' , platform , getPathJoin ( terminal ) ) ; return `${ pythonPath } -m ${ command }` ; } export async function runCommandInVenv ( command , venvName , folderPath ) { const terminal = process . platform === 'win32' ? Terminal . cmd : Terminal . bash ; command = joinCommands ( terminal , getVenvActivateCommand ( venvName , terminal , process . platform ) , command ) ; await cpUtils . executeCommand ( ext . outputChannel , folderPath , command ) ; } export async function venvExists ( venvName , rootFolder ) { const venvPath = path . join ( rootFolder , venvName ) ; if ( await fse . pathExists ( venvPath ) ) { const stat = await fse . stat ( venvPath ) ; if ( stat . isDirectory ( ) ) { const venvActivatePath = getVenvPath ( venvName , 'activate' , process . platform , path . join ) ; if ( await fse . pathExists ( path . join ( rootFolder , venvActivatePath ) ) ) { return true ; } } } return false ; } function getTerminal ( platform ) { if ( platform === 'win32' ) { if ( /(powershell|pwsh)/i . test ( vscode . env . shell ) ) { return Terminal . powerShell ; } else if ( /bash/i . test ( vscode . env . shell ) ) { return Terminal . bash ; } else { return Terminal . cmd ; } } else { return Terminal . bash ; } } function getVenvActivateCommand ( venvName , terminal , platform ) { const venvActivatePath = getVenvPath ( venvName , 'activate' , platform , getPathJoin ( terminal ) ) ; switch ( terminal ) { case Terminal . bash : return `. ${ venvActivatePath }` ; default : return venvActivatePath ; } } function getVenvPath ( venvName , lastFs , platform , pathJoin ) { const middleFs = platform === 'win32' ? 'Scripts' : 'bin' ; const paths = [ '.' , venvName , middleFs , lastFs ] ; return pathJoin ( ... paths ) ; } function getPathJoin ( terminal ) { switch ( terminal ) { case Terminal . bash : return path . posix . join ; default : return path . win32 . join ; } } function joinCommands ( terminal , ... commands ) { switch ( terminal ) { case Terminal . powerShell : return commands . join ( ' ; ' ) ; default : return commands . join ( ' && ' ) ; } } }