forked from regisf/virtualenvwrapper-powershell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVirtualEnvWrapper.psm1
394 lines (326 loc) · 10.5 KB
/
VirtualEnvWrapper.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#
# Python virtual env manager inspired by VirtualEnvWrapper
#
# Copyright (c) 2017 Regis FLORET
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
$WORKON_HOME=$Env:WORKON_HOME
$VIRTUALENWRAPPER_HOOK_DIR=''
$Version = "0.1.4"
#
# Set the default path and create the directory if don't exist
#
if (!$WORKON_HOME) {
$WORKON_HOME = "$Env:USERPROFILE\Envs"
}
if ((Test-Path $WORKON_HOME) -eq $false) {
mkdir $WORKON_HOME
}
#
# Get the absolute path for the environment
#
function Get-FullPyEnvPath($pypath) {
return ("{0}\{1}" -f $WORKON_HOME, $pypath)
}
#
# Display a formated error message
#
function Write-FormatedError($err) {
Write-Host
Write-Host " ERROR: $err" -ForegroundColor Red
Write-Host
}
#
# Display a formated success messge
#
function Write-FormatedSuccess($err) {
Write-Host
Write-Host " SUCCESS: $err" -ForegroundColor Green
Write-Host
}
#
# Common command to create the Python Virtual Environement.
# $Command contains either the Py2 or Py3 command
#
function Invoke-CreatePyEnv($Command, $Name) {
$NewEnv = Join-Path $WORKON_HOME $Name
Write-Host "Creating virtual env... "
Invoke-Expression "$Command '$NewEnv'"
$VenvScriptsPath = Join-Path $NewEnv "Scripts"
$ActivatePath = Join-Path $VenvScriptsPath "activate.ps1"
. $ActivatePath
Write-FormatedSuccess "$Name virtual environment was created and your're in."
}
#
# Create the Python Environment regardless the Python version
#
function New-PythonEnv($Name, $Append) {
BackupPath
if ($Append) {
$Env:PYTHONPATH = "$Append;$($Env:PYTHONPATH)"
}
Invoke-CreatePyEnv "virtualenv.exe" $Name
}
function BackupPath {
$Env:OLD_PYTHON_PATH = $Env:PYTHONPATH
}
function RestorePath {
$Env:PYTHONPATH = $Env:OLD_PYTHON_PATH
$Env:Path = $Env:OLD_SYSTEM_PATH
}
#
# Test if there's currently a python virtual env
#
function Get-IsInPythonVenv($Name) {
if ($Env:VIRTUAL_ENV) {
if ($Name) {
if (([string]$Env:VIRTUAL_ENV).EndsWith($Name)) {
return $true
}
return $false;
}
return $true
}
return $false
}
# Now, work on a env
function Workon {
Param(
[string] $Name
)
if (!$Name) {
Write-FormatedError "No python venv to work on. Did you forget the -Name option?"
return
}
$new_pyenv = Get-FullPyEnvPath $Name
if ((Test-Path $new_pyenv) -eq $false) {
Write-FormatedError "The Python environment '$Name' don't exists. You may want to create it with 'MkVirtualEnv $Name'"
return
}
if (Get-IsInPythonVenv -eq $true) {
deactivate
}
$activate_path = "$new_pyenv\Scripts\Activate.ps1"
if ((Test-path $activate_path) -eq $false) {
Write-FormatedError "Enable to find the activation script. You Python environment $Name seems compromized"
return
}
Import-Module $activate_path -Force
$Env:OLD_PYTHON_PATH = $Env:PYTHON_PATH
$Env:VIRTUAL_ENV = "$new_pyenv"
if ((Test-path "$new_pyenv\.project") -eq $true) {
Get-Content -Encoding UTF8 "$new_pyenv\.project" | Set-Location
}
}
#
# Create a new virtual environment.
#
function New-VirtualEnv()
{
Param(
[Parameter(HelpMessage="The virtual env name")]
[string]$Name,
[Parameter(HelpMessage="The requirements file")]
[alias("r")]
[string]$Requirement,
[Parameter(HelpMessage="The package to install. Repeat the parameter for more than one")]
[alias("i")]
[string[]]$Packages,
[Parameter(HelpMessage="Associate an existing project directory to the new environment")]
[alias("a")]
[string]$Associate
)
if ($Name.StartsWith("-")) {
Write-FormatedError "The virtual environment name couldn't start with - (minus)"
return
}
if ($Append -and !(Test-Path $Append)) {
Write-FormatedError "The path '$Append' doesn't exist"
return
}
if (!$Name) {
Write-FormatedError "You must at least give me a PyEnv name"
return
}
if ((IsPyEnvExists $Name) -eq $true) {
Write-FormatedError "There is an environment with the same name"
return
}
New-PythonEnv -Name $Name -Append $Append
foreach($Package in $Packages) {
Invoke-Expression "$WORKON_HOME\$Name\Scripts\pip.exe install $Package"
}
if ($Requirement -ne "") {
if (! $(Test-Path $Requirement)) {
Write-Error "The requirement file doesn't exist"
Break
}
Invoke-Expression "$WORKON_HOME\$Name\Scripts\pip.exe install -r $Requirement"
}
if ($Associate) {
$NewEnv = Join-Path $WORKON_HOME $Name
Set-Content -Encoding UTF8 "$NewEnv\.project" (Resolve-Path $Associate)
}
}
#
# Check if there is an environment named $Name
#
function IsPyEnvExists($Name) {
$children = Get-ChildItem $WORKON_HOME
if ($children.Length -gt 0) {
for ($i=0; $i -lt $children.Length; $i++) {
if (([string]$children[$i]).CompareTo($Name) -eq 0) {
return $true
}
}
}
return $false
}
function Get-VirtualEnvs {
$children = Get-ChildItem $WORKON_HOME
Write-Host
Write-Host "`tPython Virtual Environments available"
Write-Host
Write-host ("`t{0,-30}{1,-15}" -f "Name", "Python version")
Write-host ("`t{0,-30}{1,-15}" -f "====", "==============")
Write-Host
if ($children.Length) {
$failed = [System.Collections.ArrayList]@()
for($i = 0; $i -lt $children.Length; $i++) {
$child = $children[$i]
try {
$PythonVersion = (((Invoke-Expression ("$WORKON_HOME\{0}\Scripts\Python.exe --version 2>&1" -f $child.name)) -replace "`r|`n","") -Split " ")[1]
Write-host ("`t{0,-30}{1,-15}" -f $child.name,$PythonVersion)
} catch {
$failed += $child
}
}
} else {
Write-Host "`tNo Python Environments"
}
if ($failed.Length -gt 0) {
Write-Host
Write-Host "`tAdditionally, one or more environments failed to be listed"
Write-Host "`t=========================================================="
Write-Host
foreach ($item in $failed) {
Write-Host "`t$item"
}
}
Write-Host
}
#
# Remove a virtual environment.
#
function Remove-VirtualEnv {
Param(
[string]$Name
)
if ((Get-IsInPythonVenv $Name) -eq $true) {
Write-FormatedError "You want to destroy the Virtual Env you are in. Please type 'deactivate' before to dispose the environment before"
return
}
if (!$Name) {
Write-FormatedError "You must fill a environmennt name"
return
}
$full_path = Get-FullPyEnvPath $Name
if ((Test-Path $full_path) -eq $true) {
Remove-Item -Path $full_path -Recurse
Write-FormatedSuccess "$Name was deleted permanently"
} else {
Write-FormatedError "$Name not found"
}
}
<#
.Synopsis
Get the current version of VirtualEnvWrapper
#>
function Get-VirtualEnvVersion() {
Write-Host "Version $Version"
}
<#
.Synopsis
Create a temporary environment.
#>
function New-TemporaryVirtualEnv() {
Param(
[Parameter(HelpMessage="Change directory into the newly created virtual environment")]
[alias("c")]
[switch]
$Cd = $False,
[Parameter(HelpMessage="Don't change directory")]
[alias("n")]
[switch]$NoCd = $false,
# Reimplement New-VirtualEnv parameters
[Parameter(HelpMessage="The requirements file")]
[alias("r")]
[string]$Requirement,
[Parameter(HelpMessage="The Python directory where the python.exe lives")]
[string]$Python,
[Parameter(HelpMessage="The package to install. Repeat the parameter for more than one")]
[alias("i")]
[string[]]$Packages,
[Parameter(HelpMessage="Associate an existing project directory to the new environment")]
[alias("a")]
[string]$Associate
)
Begin
{
if ($NoCd -eq $true) {
$Cd = $false;
}
}
Process
{
$uuid = (Invoke-Expression "python -c 'import uuid; print(str(uuid.uuid4()))'")
$dest_dir = "$WORKON_HOME/$uuid"
# Recompose command line
$args = ""
foreach($param in $PSBoundParameters.GetEnumerator())
{
$args += (" -{0} {1}" -f $param.Key,$param.Value)
}
Invoke-Expression "New-VirtualEnv $uuid $args"
$message = "This is a temporary environment. It will be deleted when you run 'deactivate'."
Write-Host $message
$message | Out-File -FilePath "$dest_dir/README.tmpenv"
# Write deactivation file. See Workon rewriting deactivate feature
$post_deactivate_file_content = @"
if ((est-Path -Path `"$dest_dir/README.tmpenv`") {
Write-Host `"Removing temporary environment $uuid`"
# Change the location else MS Windows will refuse to remove the directory
Set-Location `"$WORKON_HOME`"
Remove-VirtualEnv $uuid
}
"@
$post_deactivate_file_content | Out-File -FilePath "$WORKON_HOME/$uuid/postdeactivate.ps1"
if ($Cd -Eq $true) {
Set-Location -Path "$WORKON_HOME/$uuid"
}
}
}
#
# Powershell alias for naming convention
#
Set-Alias lsvirtualenv Get-VirtualEnvs
Set-Alias rmvirtualenv Remove-VirtualEnv
Set-Alias mkvirtualenv New-VirtualEnv
Set-Alias mktmpenv New-TemporaryVirtualEnv
Write-Host "Virtual Env Wrapper for Powershell activated"