juc500 정상동작

This commit is contained in:
Macbook
2026-07-21 21:04:25 +09:00
parent ff60cee1cc
commit 1388668b56
2917 changed files with 708021 additions and 651 deletions
@@ -0,0 +1,21 @@
from __future__ import annotations
from .bash import BashActivator
from .batch import BatchActivator
from .cshell import CShellActivator
from .fish import FishActivator
from .nushell import NushellActivator
from .powershell import PowerShellActivator
from .python import PythonActivator
from .xonsh import XonshActivator
__all__ = [
"BashActivator",
"BatchActivator",
"CShellActivator",
"FishActivator",
"NushellActivator",
"PowerShellActivator",
"PythonActivator",
"XonshActivator",
]
@@ -0,0 +1,61 @@
from __future__ import annotations
import os
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from argparse import ArgumentParser
from pathlib import Path
from python_discovery import PythonInfo
from virtualenv.config.cli.parser import VirtualEnvOptions
from virtualenv.create.creator import Creator
class Activator(ABC):
"""Generates activate script for the virtual environment."""
def __init__(self, options: VirtualEnvOptions) -> None:
"""Create a new activator generator.
:param options: the parsed options as defined within :meth:`add_parser_arguments`
"""
self.flag_prompt = os.path.basename(os.getcwd()) if options.prompt == "." else options.prompt
@classmethod
def supports(cls, interpreter: PythonInfo) -> bool: # noqa: ARG003
"""Check if the activation script is supported in the given interpreter.
:param interpreter: the interpreter we need to support
:returns: ``True`` if supported, ``False`` otherwise
"""
return True
@classmethod # noqa: B027
def add_parser_arguments(cls, parser: ArgumentParser, interpreter: PythonInfo) -> None:
"""Add CLI arguments for this activation script.
:param parser: the CLI parser
:param interpreter: the interpreter this virtual environment is based of
"""
@abstractmethod
def generate(self, creator: Creator) -> list[Path]:
"""Generate activate script for the given creator.
:param creator: the creator (based of :class:`virtualenv.create.creator.Creator`) we used to create this virtual
environment
"""
raise NotImplementedError
__all__ = [
"Activator",
]
@@ -0,0 +1,32 @@
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from virtualenv.create.creator import Creator
class BashActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate.sh"
def as_name(self, template: str) -> str:
return Path(template).stem
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]:
data = super().replacements(creator, dest_folder)
data.update({
"__TCL_LIBRARY__": getattr(creator.interpreter, "tcl_lib", None) or "",
"__TK_LIBRARY__": getattr(creator.interpreter, "tk_lib", None) or "",
})
return data
__all__ = [
"BashActivator",
]
@@ -0,0 +1,130 @@
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
if [ "${BASH_SOURCE-}" = "$0" ]; then
echo "You must source this script: \$ source $0" >&2
exit 33
fi
deactivate () {
unset -f pydoc >/dev/null 2>&1 || true
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="$_OLD_VIRTUAL_PATH"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
if [ -n "${_OLD_VIRTUAL_TCL_LIBRARY:-}" ]; then
TCL_LIBRARY="$_OLD_VIRTUAL_TCL_LIBRARY"
export TCL_LIBRARY
unset _OLD_VIRTUAL_TCL_LIBRARY
fi
if [ -n "${_OLD_VIRTUAL_TK_LIBRARY:-}" ]; then
TK_LIBRARY="$_OLD_VIRTUAL_TK_LIBRARY"
export TK_LIBRARY
unset _OLD_VIRTUAL_TK_LIBRARY
fi
if [ -n "${_OLD_PKG_CONFIG_PATH:-}" ]; then
PKG_CONFIG_PATH="$_OLD_PKG_CONFIG_PATH"
export PKG_CONFIG_PATH
unset _OLD_PKG_CONFIG_PATH
fi
# The hash command must be called to get it to forget past
# commands. Without forgetting past commands the $PATH changes
# we made may not be respected
hash -r 2>/dev/null || true
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="$_OLD_VIRTUAL_PS1"
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
if [ ! -d __VIRTUAL_ENV__ ]; then
echo "Virtual environment directory __VIRTUAL_ENV__ does not exist!" >&2
CURRENT_PATH=$(realpath "${BASH_SOURCE[0]}")
CURRENT_DIR=$(dirname "${CURRENT_PATH}")
VIRTUAL_ENV="$(realpath "${CURRENT_DIR}/../")"
else
VIRTUAL_ENV=__VIRTUAL_ENV__
fi
case "$(uname)" in
CYGWIN*|MSYS*|MINGW*)
VIRTUAL_ENV=$(cygpath "$VIRTUAL_ENV")
;;
esac
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"__BIN_NAME__":$PATH"
export PATH
_OLD_PKG_CONFIG_PATH="${PKG_CONFIG_PATH:-}"
PKG_CONFIG_PATH="${VIRTUAL_ENV}/lib/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}}"
export PKG_CONFIG_PATH
if [ "x"__VIRTUAL_PROMPT__ != x ] ; then
VIRTUAL_ENV_PROMPT=__VIRTUAL_PROMPT__
else
VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV")
fi
export VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if set
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
unset PYTHONHOME
fi
if [ __TCL_LIBRARY__ != "" ]; then
if [ -n "${TCL_LIBRARY:-}" ] ; then
_OLD_VIRTUAL_TCL_LIBRARY="$TCL_LIBRARY"
fi
TCL_LIBRARY=__TCL_LIBRARY__
export TCL_LIBRARY
fi
if [ __TK_LIBRARY__ != "" ]; then
if [ -n "${TK_LIBRARY:-}" ] ; then
_OLD_VIRTUAL_TK_LIBRARY="$TK_LIBRARY"
fi
TK_LIBRARY=__TK_LIBRARY__
export TK_LIBRARY
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1-}"
PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}"
fi
# Make sure to unalias pydoc if it's already there
alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
pydoc () {
python -m pydoc "$@"
}
# The hash command must be called to get it to forget past
# commands. Without forgetting past commands the $PATH changes
# we made may not be respected
hash -r 2>/dev/null || true
@@ -0,0 +1,38 @@
from __future__ import annotations
import os
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from python_discovery import PythonInfo
from virtualenv.create.creator import Creator
class BatchActivator(ViaTemplateActivator):
@classmethod
def supports(cls, interpreter: PythonInfo) -> bool:
return interpreter.os == "nt"
def templates(self) -> Iterator[str]:
yield "activate.bat"
yield "deactivate.bat"
yield "pydoc.bat"
@staticmethod
def quote(string: str) -> str:
return string
def instantiate_template(self, replacements: dict[str, str], template: str, creator: Creator) -> str:
# ensure the text has all newlines as \r\n - required by batch
base = super().instantiate_template(replacements, template, creator)
return base.replace(os.linesep, "\n").replace("\n", os.linesep)
__all__ = [
"BatchActivator",
]
@@ -0,0 +1,59 @@
@REM This file is UTF-8 encoded, so we need to update the current code page while executing it
@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
@if defined _OLD_CODEPAGE (
"%SystemRoot%\System32\chcp.com" 65001 > nul
)
@set "VIRTUAL_ENV=__VIRTUAL_ENV__"
@set "VIRTUAL_ENV_PROMPT=__VIRTUAL_PROMPT__"
@if NOT DEFINED VIRTUAL_ENV_PROMPT (
@for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
)
@if defined _OLD_VIRTUAL_PROMPT (
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
) else (
@if not defined PROMPT (
@set "PROMPT=$P$G"
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
)
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
)
@REM Don't use () to avoid problems with them in %PATH%
@if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
:ENDIFVHOME
@set PYTHONHOME=
@if defined TCL_LIBRARY @set "_OLD_VIRTUAL_TCL_LIBRARY=%TCL_LIBRARY%"
@if NOT "__TCL_LIBRARY__"=="" @set "TCL_LIBRARY=__TCL_LIBRARY__"
@if defined TK_LIBRARY @set "_OLD_VIRTUAL_TK_LIBRARY=%TK_LIBRARY%"
@if NOT "__TK_LIBRARY__"=="" @set "TK_LIBRARY=__TK_LIBRARY__"
@if defined PKG_CONFIG_PATH @set "_OLD_PKG_CONFIG_PATH=%PKG_CONFIG_PATH%"
@set "PKG_CONFIG_PATH=%VIRTUAL_ENV%\lib\pkgconfig;%PKG_CONFIG_PATH%"
@REM if defined _OLD_VIRTUAL_PATH (
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
@set "PATH=%_OLD_VIRTUAL_PATH%"
:ENDIFVPATH1
@REM ) else (
@if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
@set "_OLD_VIRTUAL_PATH=%PATH%"
:ENDIFVPATH2
@set "PATH=%VIRTUAL_ENV%\__BIN_NAME__;%PATH%"
@if defined _OLD_CODEPAGE (
"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
@set _OLD_CODEPAGE=
)
@@ -0,0 +1,30 @@
@set VIRTUAL_ENV=
@set VIRTUAL_ENV_PROMPT=
@REM Don't use () to avoid problems with them in %PATH%
@if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
@set _OLD_VIRTUAL_PROMPT=
:ENDIFVPROMPT
@if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
@set _OLD_VIRTUAL_PYTHONHOME=
:ENDIFVHOME
@if defined _OLD_VIRTUAL_TCL_LIBRARY @set "TCL_LIBRARY=%_OLD_VIRTUAL_TCL_LIBRARY%"
@if not defined _OLD_VIRTUAL_TCL_LIBRARY @set TCL_LIBRARY=
@set _OLD_VIRTUAL_TCL_LIBRARY=
@if defined _OLD_VIRTUAL_TK_LIBRARY @set "TK_LIBRARY=%_OLD_VIRTUAL_TK_LIBRARY%"
@if not defined _OLD_VIRTUAL_TK_LIBRARY @set TK_LIBRARY=
@set _OLD_VIRTUAL_TK_LIBRARY=
@if defined _OLD_PKG_CONFIG_PATH @set "PKG_CONFIG_PATH=%_OLD_PKG_CONFIG_PATH%"
@if not defined _OLD_PKG_CONFIG_PATH @set PKG_CONFIG_PATH=
@set _OLD_PKG_CONFIG_PATH=
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
@set "PATH=%_OLD_VIRTUAL_PATH%"
@set _OLD_VIRTUAL_PATH=
:ENDIFVPATH
@@ -0,0 +1 @@
"python.exe" -m pydoc %*
@@ -0,0 +1,24 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from python_discovery import PythonInfo
class CShellActivator(ViaTemplateActivator):
@classmethod
def supports(cls, interpreter: PythonInfo) -> bool:
return interpreter.os != "nt"
def templates(self) -> Iterator[str]:
yield "activate.csh"
__all__ = [
"CShellActivator",
]
@@ -0,0 +1,74 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
set newline='\
'
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_TCL_LIBRARY != 0 && setenv TCL_LIBRARY "$_OLD_VIRTUAL_TCL_LIBRARY:q" && unset _OLD_VIRTUAL_TCL_LIBRARY || unsetenv TCL_LIBRARY; test $?_OLD_VIRTUAL_TK_LIBRARY != 0 && setenv TK_LIBRARY "$_OLD_VIRTUAL_TK_LIBRARY:q" && unset _OLD_VIRTUAL_TK_LIBRARY || unsetenv TK_LIBRARY; test $?_OLD_PKG_CONFIG_PATH != 0 && setenv PKG_CONFIG_PATH "$_OLD_PKG_CONFIG_PATH:q" && unset _OLD_PKG_CONFIG_PATH || unsetenv PKG_CONFIG_PATH; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV __VIRTUAL_ENV__
set _OLD_VIRTUAL_PATH="$PATH:q"
setenv PATH "$VIRTUAL_ENV:q/"__BIN_NAME__":$PATH:q"
if ($?PKG_CONFIG_PATH) then
set _OLD_PKG_CONFIG_PATH="$PKG_CONFIG_PATH"
setenv PKG_CONFIG_PATH "${VIRTUAL_ENV}/lib/pkgconfig:${PKG_CONFIG_PATH}"
else
setenv PKG_CONFIG_PATH "${VIRTUAL_ENV}/lib/pkgconfig"
endif
if (__TCL_LIBRARY__ != "") then
if ($?TCL_LIBRARY) then
set _OLD_VIRTUAL_TCL_LIBRARY="$TCL_LIBRARY"
endif
setenv TCL_LIBRARY __TCL_LIBRARY__
endif
if (__TK_LIBRARY__ != "") then
if ($?TK_LIBRARY) then
set _OLD_VIRTUAL_TK_LIBRARY="$TK_LIBRARY"
endif
setenv TK_LIBRARY __TK_LIBRARY__
endif
if (__VIRTUAL_PROMPT__ != "") then
setenv VIRTUAL_ENV_PROMPT __VIRTUAL_PROMPT__
else
setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"
endif
if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then
if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then
set do_prompt = "1"
else
set do_prompt = "0"
endif
else
set do_prompt = "1"
endif
if ( $do_prompt == "1" ) then
# Could be in a non-interactive environment,
# in which case, $prompt is undefined and we wouldn't
# care about the prompt anyway.
if ( $?prompt ) then
set _OLD_VIRTUAL_PROMPT="$prompt:q"
if ( "$prompt:q" =~ *"$newline:q"* ) then
:
else
set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q"
endif
endif
endif
unset env_name
unset do_prompt
alias pydoc python -m pydoc
rehash
@@ -0,0 +1,29 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from virtualenv.create.creator import Creator
class FishActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate.fish"
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]:
data = super().replacements(creator, dest_folder)
data.update({
"__TCL_LIBRARY__": getattr(creator.interpreter, "tcl_lib", None) or "",
"__TK_LIBRARY__": getattr(creator.interpreter, "tk_lib", None) or "",
})
return data
__all__ = [
"FishActivator",
]
@@ -0,0 +1,124 @@
# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
# Do not run it directly.
function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n __TCL_LIBRARY__
if test -n "$_OLD_VIRTUAL_TCL_LIBRARY";
set -gx TCL_LIBRARY "$_OLD_VIRTUAL_TCL_LIBRARY";
set -e _OLD_VIRTUAL_TCL_LIBRARY;
else;
set -e TCL_LIBRARY;
end
end
if test -n __TK_LIBRARY__
if test -n "$_OLD_VIRTUAL_TK_LIBRARY";
set -gx TK_LIBRARY "$_OLD_VIRTUAL_TK_LIBRARY";
set -e _OLD_VIRTUAL_TK_LIBRARY;
else;
set -e TK_LIBRARY;
end
end
if test -n "$_OLD_PKG_CONFIG_PATH"
set -gx PKG_CONFIG_PATH "$_OLD_PKG_CONFIG_PATH"
set -e _OLD_PKG_CONFIG_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
and builtin functions -q _old_fish_prompt
# Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
set -l fish_function_path
# Erase virtualenv's `fish_prompt` and restore the original.
builtin functions -e fish_prompt
builtin functions -c _old_fish_prompt fish_prompt
builtin functions -e _old_fish_prompt
set -e _OLD_FISH_PROMPT_OVERRIDE
end
set -e VIRTUAL_ENV
set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != 'nondestructive'
# Self-destruct!
builtin functions -e pydoc
builtin functions -e deactivate
end
end
# Unset irrelevant variables.
deactivate nondestructive
set -gx VIRTUAL_ENV __VIRTUAL_ENV__
if string match -qr 'CYGWIN|MSYS|MINGW' (uname)
set -gx VIRTUAL_ENV (cygpath -u $VIRTUAL_ENV)
end
set -gx _OLD_PKG_CONFIG_PATH "$PKG_CONFIG_PATH"
set -gx PKG_CONFIG_PATH "$VIRTUAL_ENV/lib/pkgconfig:$PKG_CONFIG_PATH"
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV"'/'__BIN_NAME__ $PATH
if test -n __TCL_LIBRARY__
if set -q TCL_LIBRARY;
set -gx _OLD_VIRTUAL_TCL_LIBRARY $TCL_LIBRARY;
end
set -gx TCL_LIBRARY '__TCL_LIBRARY__'
end
if test -n __TK_LIBRARY__
if set -q TK_LIBRARY;
set -gx _OLD_VIRTUAL_TK_LIBRARY $TK_LIBRARY;
end
set -gx TK_LIBRARY '__TK_LIBRARY__'
end
# Prompt override provided?
# If not, just use the environment name.
if test -n __VIRTUAL_PROMPT__
set -gx VIRTUAL_ENV_PROMPT __VIRTUAL_PROMPT__
else
set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")
end
# Unset `$PYTHONHOME` if set.
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
function pydoc
python -m pydoc $argv
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# Copy the current `fish_prompt` function as `_old_fish_prompt`.
builtin functions -c fish_prompt _old_fish_prompt
# Route every builtin the prompt path uses through `builtin` so a user function that shadows
# `printf`, `string`, `echo`, or `source`/`.` cannot hijack the prompt (Issue #93858 follow-up,
# CPython gh-140006). A dot-style directory navigator redefining `.` is the common trigger.
function fish_prompt
set -l old_status $status
# Run the user's prompt first; it might depend on (pipe)status.
set -l prompt (_old_fish_prompt)
builtin printf '(%s) ' $VIRTUAL_ENV_PROMPT
builtin string join -- \n $prompt # handle multi-line prompts
builtin echo "exit $old_status" | builtin source -
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
end
@@ -0,0 +1,51 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from virtualenv.create.creator import Creator
class NushellActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate.nu"
@staticmethod
def quote(string: str) -> str:
"""Nushell supports raw strings like: r###'this is a string'###.
https://github.com/nushell/nushell.github.io/blob/main/book/working_with_strings.md
This method finds the maximum continuous sharps in the string and then quote it with an extra sharp.
"""
max_sharps = 0
current_sharps = 0
for char in string:
if char == "#":
current_sharps += 1
max_sharps = max(current_sharps, max_sharps)
else:
current_sharps = 0
wrapping = "#" * (max_sharps + 1)
return f"r{wrapping}'{string}'{wrapping}"
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]: # noqa: ARG002
return {
"__VIRTUAL_PROMPT__": "" if self.flag_prompt is None else self.flag_prompt,
"__VIRTUAL_ENV__": str(creator.dest),
"__VIRTUAL_NAME__": creator.env_name,
"__BIN_NAME__": str(creator.bin_dir.relative_to(creator.dest)),
"__TCL_LIBRARY__": getattr(creator.interpreter, "tcl_lib", None) or "",
"__TK_LIBRARY__": getattr(creator.interpreter, "tk_lib", None) or "",
}
__all__ = [
"NushellActivator",
]
@@ -0,0 +1,91 @@
# virtualenv activation module:
# - Activate with `overlay use activate.nu`
# - Deactivate with `deactivate`, as usual
#
# To customize the overlay name, call `overlay use activate.nu as foo`, but then `deactivate` won't work —
# you'd need to run `overlay hide foo` manually. Do not activate with `use activate.nu *`; that does not
# create an overlay and deactivation will fail.
module warning {
export-env {
const file = path self
error make -u {
msg: $"`($file | path basename)` is meant to be used with `overlay use`, not `source`"
}
}
}
use warning
export-env {
let nu_ver = (version | get version | split row '.' | take 2 | each { into int })
if $nu_ver.0 == 0 and $nu_ver.1 < 106 {
error make {
msg: 'virtualenv Nushell activation requires Nushell 0.106 or greater.'
}
}
def is-string [x] {
($x | describe) == 'string'
}
def has-env [...names] {
$names | each {|n| $n in $env } | all {|i| $i }
}
def is-env-true [name: string] {
if (has-env $name) {
let val = ($env | get --optional $name)
if ($val | describe) == 'bool' {
$val
} else {
not ($val | is-empty)
}
} else {
false
}
}
let virtual_env = __VIRTUAL_ENV__
let bin = __BIN_NAME__
let path_name = if (has-env 'Path') { 'Path' } else { 'PATH' }
let venv_path = ([$virtual_env $bin] | path join)
let new_path = ($env | get $path_name | prepend $venv_path)
let virtual_env_prompt = if (__VIRTUAL_PROMPT__ | is-empty) {
($virtual_env | path basename)
} else {
__VIRTUAL_PROMPT__
}
let old_pkg_config_path = if (has-env 'PKG_CONFIG_PATH') { $env.PKG_CONFIG_PATH } else { '' }
let new_pkg_config_path = $'($virtual_env)/lib/pkgconfig:($old_pkg_config_path)'
let new_env = { $path_name: $new_path VIRTUAL_ENV: $virtual_env VIRTUAL_ENV_PROMPT: $virtual_env_prompt PKG_CONFIG_PATH: $new_pkg_config_path }
if (has-env 'TCL_LIBRARY') {
let $new_env = $new_env | insert TCL_LIBRARY __TCL_LIBRARY__
}
if (has-env 'TK_LIBRARY') {
let $new_env = $new_env | insert TK_LIBRARY __TK_LIBRARY__
}
let old_prompt_command = if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' }
let new_env = if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
$new_env
} else {
let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
let new_prompt = if (has-env 'PROMPT_COMMAND') {
if ('closure' in ($old_prompt_command | describe)) {
{|| $'($virtual_prefix)(do $old_prompt_command)' }
} else {
{|| $'($virtual_prefix)($old_prompt_command)' }
}
} else {
{|| $'($virtual_prefix)' }
}
$new_env | merge { PROMPT_COMMAND: $new_prompt VIRTUAL_PREFIX: $virtual_prefix }
}
load-env $new_env
}
export alias pydoc = python -m pydoc
# If deactivate errors "not an active overlay": activate with `overlay use activate.nu` not `use activate.nu *`; for custom names use `overlay hide NAME`
export alias deactivate = overlay hide activate
@@ -0,0 +1,30 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
class PowerShellActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate.ps1"
@staticmethod
def quote(string: str) -> str:
"""This should satisfy PowerShell quoting rules [1], unless the quoted string is passed directly to Windows native commands [2].
[1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
[2]:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing#passing-arguments-that-contain-quote-characters
"""
string = string.replace("'", "''")
return f"'{string}'"
__all__ = [
"PowerShellActivator",
]
@@ -0,0 +1,213 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
activate.ps1
Activates the Python virtual environment that contains the activate.ps1 script.
.Example
activate.ps1 -Verbose
Activates the Python virtual environment that contains the activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse ``key = value`` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
function global:deactivate([switch] $NonDestructive) {
if (Test-Path variable:_OLD_VIRTUAL_PATH) {
$env:PATH = $variable:_OLD_VIRTUAL_PATH
Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
}
if (Test-Path variable:_OLD_VIRTUAL_TCL_LIBRARY) {
$env:TCL_LIBRARY = $variable:_OLD_VIRTUAL_TCL_LIBRARY
Remove-Variable "_OLD_VIRTUAL_TCL_LIBRARY" -Scope global
} else {
if (Test-Path env:TCL_LIBRARY) {
Remove-Item env:TCL_LIBRARY -ErrorAction SilentlyContinue
}
}
if (Test-Path variable:_OLD_VIRTUAL_TK_LIBRARY) {
$env:TK_LIBRARY = $variable:_OLD_VIRTUAL_TK_LIBRARY
Remove-Variable "_OLD_VIRTUAL_TK_LIBRARY" -Scope global
} else {
if (Test-Path env:TK_LIBRARY) {
Remove-Item env:TK_LIBRARY -ErrorAction SilentlyContinue
}
}
if (Test-Path variable:_OLD_PKG_CONFIG_PATH) {
$env:PKG_CONFIG_PATH = $variable:_OLD_PKG_CONFIG_PATH
Remove-Variable "_OLD_PKG_CONFIG_PATH" -Scope global
}
if (Test-Path function:_old_virtual_prompt) {
$function:prompt = $function:_old_virtual_prompt
Remove-Item function:\_old_virtual_prompt
}
if ($env:VIRTUAL_ENV) {
Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
}
if ($env:VIRTUAL_ENV_PROMPT) {
Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
}
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
if (!$NonDestructive) {
Remove-Item function:deactivate
Remove-Item function:pydoc
}
}
function global:pydoc {
& python -m pydoc $args
}
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
} else {
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
} else {
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose "Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt']
} elseif (__VIRTUAL_PROMPT__ -ne "") {
$Prompt = __VIRTUAL_PROMPT__
} else {
$Prompt = Split-Path -Path $VenvDir -Leaf
}
}
deactivate -nondestructive
$env:VIRTUAL_ENV = $VenvDir
$env:VIRTUAL_ENV_PROMPT = $Prompt
if (__TCL_LIBRARY__ -ne "") {
if (Test-Path env:TCL_LIBRARY) {
New-Variable -Scope global -Name _OLD_VIRTUAL_TCL_LIBRARY -Value $env:TCL_LIBRARY
}
$env:TCL_LIBRARY = __TCL_LIBRARY__
}
if (__TK_LIBRARY__ -ne "") {
if (Test-Path env:TK_LIBRARY) {
New-Variable -Scope global -Name _OLD_VIRTUAL_TK_LIBRARY -Value $env:TK_LIBRARY
}
$env:TK_LIBRARY = __TK_LIBRARY__
}
New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
if (Test-Path env:PKG_CONFIG_PATH) {
New-Variable -Scope global -Name _OLD_PKG_CONFIG_PATH -Value $env:PKG_CONFIG_PATH
}
$env:PKG_CONFIG_PATH = "$env:VIRTUAL_ENV\lib\pkgconfig;$env:PKG_CONFIG_PATH"
$env:PATH = "$env:VIRTUAL_ENV/" + __BIN_NAME__ + __PATH_SEP__ + $env:PATH
if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {
function global:_old_virtual_prompt {
""
}
$function:_old_virtual_prompt = $function:prompt
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($($_PYTHON_VENV_PROMPT_PREFIX)) "
_old_virtual_prompt
}
}
@@ -0,0 +1,39 @@
from __future__ import annotations
import os
from collections import OrderedDict
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from virtualenv.create.creator import Creator
class PythonActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate_this.py"
@staticmethod
def quote(string: str) -> str:
return repr(string)
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]:
replacements = super().replacements(creator, dest_folder)
lib_folders = OrderedDict((os.path.relpath(str(i), str(dest_folder)), None) for i in creator.libs)
lib_folders = os.pathsep.join(lib_folders.keys())
replacements.update(
{
"__LIB_FOLDERS__": lib_folders,
"__DECODE_PATH__": "",
},
)
return replacements
__all__ = [
"PythonActivator",
]
@@ -0,0 +1,45 @@
"""Activate virtualenv for current interpreter:
import runpy runpy.run_path(this_file)
This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
""" # noqa: D415
from __future__ import annotations
import os
import site
import sys
try:
abs_file = os.path.abspath(__file__)
except NameError as exc:
msg = "You must use import runpy; runpy.run_path(this_file)"
raise AssertionError(msg) from exc
bin_dir = os.path.dirname(abs_file)
base = bin_dir[: -len(__BIN_NAME__) - 1] # ty: ignore[unresolved-reference]
# prepend bin to PATH (this file is inside the bin directory)
os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])
os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
os.environ["VIRTUAL_ENV_PROMPT"] = __VIRTUAL_PROMPT__ or os.path.basename(base) # ty: ignore[unresolved-reference]
# Set PKG_CONFIG_PATH to include the virtualenv's pkgconfig directory
pkg_config_path = os.path.join(base, "lib", "pkgconfig")
existing_pkg_config_path = os.environ.get("PKG_CONFIG_PATH", "")
if existing_pkg_config_path:
os.environ["PKG_CONFIG_PATH"] = os.pathsep.join([pkg_config_path, existing_pkg_config_path])
else:
os.environ["PKG_CONFIG_PATH"] = pkg_config_path
# add the virtual environments libraries to the host python import mechanism
prev_length = len(sys.path)
for lib in __LIB_FOLDERS__.split(os.pathsep): # ty: ignore[unresolved-reference]
path = os.path.realpath(os.path.join(bin_dir, lib))
site.addsitedir(path.decode("utf-8") if __DECODE_PATH__ else path) # ty: ignore[unresolved-reference,unresolved-attribute]
sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
sys.real_prefix = sys.prefix # ty: ignore[unresolved-attribute]
sys.prefix = base
@@ -0,0 +1,99 @@
from __future__ import annotations
import os
import shlex
import sys
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
from .activator import Activator
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
from pathlib import Path
from virtualenv.create.creator import Creator
if sys.version_info >= (3, 10):
from importlib.resources import files
def read_binary(module_name: str, filename: str) -> bytes:
return (files(module_name) / filename).read_bytes()
else:
from importlib.resources import read_binary
class ViaTemplateActivator(Activator, ABC):
@abstractmethod
def templates(self) -> Iterator[str]:
raise NotImplementedError
@staticmethod
def quote(string: str) -> str:
"""Quote strings in the activation script.
:param string: the string to quote
:returns: quoted string that works in the activation script
"""
return shlex.quote(string)
def generate(self, creator: Creator) -> list[Path]:
dest_folder = creator.bin_dir
replacements = self.replacements(creator, dest_folder)
generated = self._generate(replacements, self.templates(), dest_folder, creator)
if self.flag_prompt is not None:
creator.pyenv_cfg["prompt"] = self.flag_prompt
return generated
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]: # noqa: ARG002
return {
"__VIRTUAL_PROMPT__": "" if self.flag_prompt is None else self.flag_prompt,
"__VIRTUAL_ENV__": str(creator.dest),
"__VIRTUAL_NAME__": creator.env_name,
"__BIN_NAME__": str(creator.bin_dir.relative_to(creator.dest)),
"__PATH_SEP__": os.pathsep,
"__TCL_LIBRARY__": getattr(creator.interpreter, "tcl_lib", None) or "",
"__TK_LIBRARY__": getattr(creator.interpreter, "tk_lib", None) or "",
}
def _generate(
self, replacements: dict[str, str], templates: Iterable[str], to_folder: Path, creator: Creator
) -> list[Path]:
generated = []
for template in templates:
text = self.instantiate_template(replacements, template, creator)
dest = to_folder / self.as_name(template)
# remove the file if it already exists - this prevents permission
# errors when the dest is not writable
if dest.exists():
dest.unlink()
# Powershell assumes Windows 1252 encoding when reading files without BOM
encoding = "utf-8-sig" if str(template).endswith(".ps1") else "utf-8"
# use write_bytes to avoid platform specific line normalization (\n -> \r\n)
dest.write_bytes(text.encode(encoding))
generated.append(dest)
return generated
def as_name(self, template: str) -> str:
return template
def instantiate_template(self, replacements: dict[str, str], template: str, creator: Creator) -> str:
# read content as binary to avoid platform specific line normalization (\n -> \r\n)
binary = read_binary(self.__module__, template)
text = binary.decode("utf-8", errors="strict")
for key, value in replacements.items():
value_uni = self._repr_unicode(creator, value)
text = text.replace(key, self.quote(value_uni))
return text
@staticmethod
def _repr_unicode(creator: Creator, value: str) -> str: # noqa: ARG004
return value # by default, we just let it be unicode
__all__ = [
"ViaTemplateActivator",
]
@@ -0,0 +1,34 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from virtualenv.activation.via_template import ViaTemplateActivator
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from virtualenv.create.creator import Creator
class XonshActivator(ViaTemplateActivator):
def templates(self) -> Iterator[str]:
yield "activate.xsh"
@staticmethod
def quote(string: str) -> str:
"""Quote as a Python literal — xonsh parses the activation script as Python."""
return repr(string)
def replacements(self, creator: Creator, dest_folder: Path) -> dict[str, str]:
data = super().replacements(creator, dest_folder)
data.update({
"__TCL_LIBRARY__": getattr(creator.interpreter, "tcl_lib", None) or "",
"__TK_LIBRARY__": getattr(creator.interpreter, "tk_lib", None) or "",
})
return data
__all__ = [
"XonshActivator",
]
@@ -0,0 +1,101 @@
# This file must be used with "source bin/activate.xsh" *from xonsh*.
# You cannot run it directly.
class _VirtualEnvActivator:
"""xonsh activation for virtualenv.
Rendered into ``<venv>/bin/activate.xsh`` by the template in
``src/virtualenv/activation/xonsh/`` at generate-time.
- Project: https://github.com/pypa/virtualenv
- Template source: https://github.com/pypa/virtualenv/tree/main/src/virtualenv/activation/xonsh
"""
# Stashed in _OLD_VIRTUAL_{name} when the variable was not set before
# activation. deactivate treats this as "unset" rather than "restore to
# this string". Chosen to be vanishingly unlikely as a real value.
_UNSET_SENTINEL = "__virtualenv_was_not_set__"
def __init__(self):
self.env = __xonsh__.env
try:
# Values substituted by virtualenv's XonshActivator at generate-time.
# If this file was sourced before template rendering, the bare
# identifiers below resolve to NameError.
self.embedded_virtual_env = __VIRTUAL_ENV__
self.embedded_virtual_prompt = __VIRTUAL_PROMPT__
self.embedded_bin_name = __BIN_NAME__
self.embedded_tcl_library = __TCL_LIBRARY__
self.embedded_tk_library = __TK_LIBRARY__
except NameError:
print("virtualenv activate.xsh: template was not rendered")
raise
# Variables this activator may save+override; deactivate walks this list.
self.managed_vars = ("PATH", "PYTHONHOME", "TCL_LIBRARY", "TK_LIBRARY")
def _backup_name(self, name):
return f"_OLD_VIRTUAL_{name}"
def _save(self, name):
"""Stash the current value (or sentinel if unset) so deactivate can undo."""
backup = self._backup_name(name)
self.env[backup] = self.env[name] if name in self.env else self._UNSET_SENTINEL
def _override(self, name, value):
self._save(name)
self.env[name] = value
def _drop(self, name):
self._save(name)
self.env.pop(name, None)
def register_pydoc(self):
aliases["pydoc"] = ["python", "-m", "pydoc"]
def unregister_pydoc(self):
aliases.pop("pydoc", None)
def activate(self):
from os.path import join, basename
aliases["deactivate"] = self.deactivate
self.deactivate(["nondestructive"]) # wipe any stale state from a prior activation
$VIRTUAL_ENV = self.embedded_virtual_env
$VIRTUAL_ENV_PROMPT = self.embedded_virtual_prompt or basename($VIRTUAL_ENV)
self._override("PATH", [join($VIRTUAL_ENV, self.embedded_bin_name), *$PATH])
self._drop("PYTHONHOME")
for name, value in (("TCL_LIBRARY", self.embedded_tcl_library), ("TK_LIBRARY", self.embedded_tk_library)):
if value:
self._override(name, value)
self.register_pydoc()
def deactivate(self, args=None):
for name in self.managed_vars:
backup = self._backup_name(name)
if backup not in self.env:
continue
previous = self.env[backup]
del self.env[backup]
if previous == self._UNSET_SENTINEL:
self.env.pop(name, None)
else:
self.env[name] = previous
for name in ("VIRTUAL_ENV", "VIRTUAL_ENV_PROMPT"):
self.env.pop(name, None)
self.unregister_pydoc()
if args is None or "nondestructive" not in args:
del aliases["deactivate"]
try:
del __xonsh__.xontrib.virtualenv
except AttributeError:
pass
if not hasattr(__xonsh__, "xontrib"):
__xonsh__.xontrib = __xonsh__.imp.types.SimpleNamespace()
__xonsh__.xontrib.virtualenv = _VirtualEnvActivator()
__xonsh__.xontrib.virtualenv.activate()