Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- param (
- [Parameter(Mandatory=$true)]
- [ValidateSet('activate', 'init')]
- [string]$Command,
- [string]$VersionString
- )
- function Get-ExistingVirtualEnvironment {
- $directoryNames = '.venv', 'venv', '.env', 'env', '.penv', 'penv'
- foreach ($name in $directoryNames) {
- $activateScript = [IO.Path]::Combine($(Get-Location), $name, 'Scripts', 'Activate.ps1')
- if (Test-Path -LiteralPath $activateScript) {
- return $name
- }
- }
- return $null
- }
- function Initialize-VirtualEnvironment($folderpath) {
- $activateScript = [IO.Path]::Combine($folderpath, 'Scripts', 'Activate.ps1')
- # Create virtual environment if it doesn't already exist
- if (Test-Path $activateScript) {
- throw "Environment already exists: $($folderpath)"
- }
- python -m venv $folderpath
- if ($LastExitCode -ne 0) {
- throw "Failed to create virtual environment with: 'python -m venv $($folderpath)'"
- }
- # Ensure virtual environment's activate script exist
- if (-not (Test-Path $activateScript)) {
- throw 'Virtual environment or activate script not found'
- }
- & $activateScript
- }
- # Ensure we have python
- if ((Get-Command 'python' -ErrorAction SilentlyContinue) -eq $null) {
- throw 'Python was not found'
- }
- switch ($Command) {
- 'activate' {
- $virtualEnvName = Get-ExistingVirtualEnvironment
- if ($virtualEnvName) {
- & $([IO.Path]::Combine($(Get-Location), $virtualEnvName, 'Scripts', 'Activate.ps1'))
- } else {
- throw 'No virtual environment directory found in the current directory.'
- }
- }
- 'init' {
- if ($VersionString) {
- pyenv local $version
- } else {
- pyenv local 3.12.2
- }
- $existing = Get-ExistingVirtualEnvironment
- if ($existing) {
- # $confirmation = Read-Host "An existing virtual environment was found. Overwrite? (Y/n)"
- $choice = $Host.UI.PromptForChoice(
- "An existing virtual environment was found: '$($existing)/'",
- "Overwrite?",
- @('&Yes'; '&No'),
- 0
- )
- if ($choice -eq 0) {
- Remove-Item -LiteralPath $existing -Recurse
- }
- else { exit }
- }
- Initialize-VirtualEnvironment('.venv')
- }
- }
- # Ensure Python is running in a virtual environment
- python -c 'import sys;sys.exit(0 if sys.prefix != sys.base_prefix else -1)'
- if ($LastExitCode -ne 0) {
- throw 'Python was not virtualized'
- }
- echo ---
- echo 'Python Virtual Environment Started'
- echo "Running $(python --version)"
- echo "Located from $(Get-Command python | Select Source -ExpandProperty Source)"
- echo ---
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement