mirror of
https://github.com/xonsh/xonsh.git
synced 2025-03-04 16:34:47 +01:00
modify expandvars to use the xonsh environment
This commit is contained in:
parent
f958b8b04a
commit
8299ce49ea
2 changed files with 45 additions and 2 deletions
|
@ -22,7 +22,7 @@ from collections import Sequence, MutableMapping, Iterable, namedtuple, \
|
|||
MutableSequence, MutableSet
|
||||
|
||||
from xonsh.tools import suggest_commands, XonshError, ON_POSIX, ON_WINDOWS, \
|
||||
string_types
|
||||
string_types, expandvars
|
||||
from xonsh.inspectors import Inspector
|
||||
from xonsh.environ import Env, default_env, locate_binary
|
||||
from xonsh.aliases import DEFAULT_ALIASES
|
||||
|
@ -183,7 +183,7 @@ def expand_path(s):
|
|||
if ENV is not None:
|
||||
ENV.replace_env()
|
||||
if ENV.get('EXPAND_ENV_VARS'):
|
||||
s = os.path.expandvars(s)
|
||||
s = expandvars(s)
|
||||
return os.path.expanduser(s)
|
||||
|
||||
|
||||
|
|
|
@ -909,3 +909,46 @@ def check_for_partial_string(x):
|
|||
return (string_indices[-1], None, starting_quote[-1])
|
||||
else:
|
||||
return (string_indices[-2], string_indices[-1], starting_quote[-1])
|
||||
|
||||
|
||||
# expandvars is a modified version of os.path.expandvars from the Python 3.5.1
|
||||
# source code (root/Lib/posixpath.py, line 266)
|
||||
|
||||
_varprog = None
|
||||
|
||||
|
||||
def expandvars(path):
|
||||
"""Expand shell variables of form $var and ${var}. Unknown variables
|
||||
are left unchanged."""
|
||||
global _varprog
|
||||
ENV = builtins.__xonsh_env__
|
||||
if isinstance(path, bytes):
|
||||
path = path.decode(encoding=env.get('XONSH_ENCODING'),
|
||||
errors=env.get('XONSH_ENCODING_ERRORS'))
|
||||
if '$' not in path:
|
||||
return path
|
||||
if not _varprog:
|
||||
import re
|
||||
_varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
|
||||
search = _varprog.search
|
||||
start = '{'
|
||||
end = '}'
|
||||
i = 0
|
||||
while True:
|
||||
m = search(path, i)
|
||||
if not m:
|
||||
break
|
||||
i, j = m.span(0)
|
||||
name = m.group(1)
|
||||
if name.startswith(start) and name.endswith(end):
|
||||
name = eval(name[1:-1]) # change for non-POSIX ${...}
|
||||
try:
|
||||
value = ENV.get(name)
|
||||
except KeyError:
|
||||
i = j
|
||||
else:
|
||||
tail = path[j:]
|
||||
path = path[:i] + value
|
||||
i = len(path)
|
||||
path += tail
|
||||
return path
|
||||
|
|
Loading…
Add table
Reference in a new issue