1
Fork 0
mirror of https://github.com/RGBCube/nu_scripts synced 2025-08-01 22:57:46 +00:00
nu_scripts/modules/virtual_environments/auto-venv/venv_helpers.nu
Elizabeth eedcd10dbb
Fixed sys usage (#916)
Just as a heads up, I haven't really tested this since a lot of it is
stuff I don't use or know how to set up without some reading up. I have
tested the nu_conda_2 change since I have a python project that I use
that for, and I could look into testing more of it if needed.

I've tried finding (naively using `/sys\W/`) all the usage of the old
plain `sys` calls and replacing them with alternates as appropriate,
which mostly has been to swap a `(sys).host.name` call into a
`$nu.os-info.name` one, since it'll be tad faster and more consistent
across platforms with naming (especially as the value comes from the
[rust stdlib](https://doc.rust-lang.org/std/env/consts/constant.OS.html)
and is very predictable).

Fixes #897
2024-07-24 09:09:31 -05:00

90 lines
1.8 KiB
Text

use path_extensions.nu *
def has-sub [
folder: string,
subfolder: string
] {
not (path find-sub $folder $subfolder | is-empty);
}
def get-env [
name: string
default: any
] {
(if ($name in $env) {
$env | get $name
}
else {
$default
})
}
export def venv-is-active [] {
'__auto_venv' in (overlay list)
}
# Creates a virtual environment under the current directory
export def 'venv-create' [] {
let venv_path = $env.PWD
let venv_name = ($env.PWD | path basename)
let is_posix = ($nu.os-info.family == 'unix')
let python_name = if $is_posix {'python3'} else {'py.exe'}
run-external $python_name "-m" "venv" ".venv" "--clear" "--prompt" $venv_name
run-external $".venv/bin/($python_name)" "-m" "pip" "install" "-U" "pip" "wheel" "setuptools"
let trigger_file = ([$env.PWD, $env.AUTO_VENV_TRIGGER] | path join)
ln -sf $'($env.FILE_PWD)/venvs/python-venv.nu' $trigger_file
}
export def has-entered-venv [
after: path,
] {
let target = (path find-sub $after $env.AUTO_VENV_TRIGGER)
(if ($target | is-empty) {
false
}
else {
# if venv is already active, handle it in "venv swap" hook
not (venv-is-active)
})
}
export def has-swapped-venv [
after: path,
] {
(if not (venv-is-active) {
false
}
else {
let target = (path find-sub $after $env.AUTO_VENV_TRIGGER)
(if ($target | is-empty) {
false
}
else {
(if ('VIRTUAL_ENV' in $env) {
$env.VIRTUAL_ENV != $target
} else {
false # should it default to `false`?
})
})
})
}
export def has-exited-venv [
after: path,
] {
(if not (venv-is-active) {
false
}
else {
not (has-sub $after $env.AUTO_VENV_TRIGGER)
})
}