forked from xonsh/xonsh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
built_ins.py
744 lines (620 loc) · 21.5 KB
/
built_ins.py
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
"""The xonsh built-ins.
Note that this module is named 'built_ins' so as not to be confused with the
special Python builtins module.
"""
import atexit
import builtins
import collections.abc as cabc
import contextlib
import inspect
import itertools
import os
import pathlib
import re
import signal
import sys
import types
import warnings
from ast import AST
from xonsh.inspectors import Inspector
from xonsh.lazyasd import lazyobject
from xonsh.platform import ON_POSIX
from xonsh.tools import (
XonshCalledProcessError,
XonshError,
expand_path,
globpath,
print_color,
)
INSPECTOR = Inspector()
warnings.filterwarnings("once", category=DeprecationWarning)
@lazyobject
def AT_EXIT_SIGNALS():
sigs = (
signal.SIGABRT,
signal.SIGFPE,
signal.SIGILL,
signal.SIGSEGV,
signal.SIGTERM,
)
if ON_POSIX:
sigs += (signal.SIGTSTP, signal.SIGQUIT, signal.SIGHUP)
return sigs
def resetting_signal_handle(sig, f):
"""Sets a new signal handle that will automatically restore the old value
once the new handle is finished.
"""
oldh = signal.getsignal(sig)
def newh(s=None, frame=None):
f(s, frame)
signal.signal(sig, oldh)
if sig != 0:
sys.exit(sig)
signal.signal(sig, newh)
def helper(x, name=""):
"""Prints help about, and then returns that variable."""
name = name or getattr(x, "__name__", "")
INSPECTOR.pinfo(x, oname=name, detail_level=0)
return x
def superhelper(x, name=""):
"""Prints help about, and then returns that variable."""
name = name or getattr(x, "__name__", "")
INSPECTOR.pinfo(x, oname=name, detail_level=1)
return x
def reglob(path, parts=None, i=None):
"""Regular expression-based globbing."""
if parts is None:
path = os.path.normpath(path)
drive, tail = os.path.splitdrive(path)
parts = tail.split(os.sep)
d = os.sep if os.path.isabs(path) else "."
d = os.path.join(drive, d)
return reglob(d, parts, i=0)
base = subdir = path
if i == 0:
if not os.path.isabs(base):
base = ""
elif len(parts) > 1:
i += 1
try:
regex = re.compile(parts[i])
except Exception as e:
if isinstance(e, re.error) and str(e) == "nothing to repeat at position 0":
raise XonshError(
"Consider adding a leading '.' to your glob regex pattern."
)
else:
raise e
files = os.listdir(subdir)
files.sort()
paths = []
i1 = i + 1
if i1 == len(parts):
for f in files:
p = os.path.join(base, f)
if regex.fullmatch(f) is not None:
paths.append(p)
else:
for f in files:
p = os.path.join(base, f)
if regex.fullmatch(f) is None or not os.path.isdir(p):
continue
paths += reglob(p, parts=parts, i=i1)
return paths
def path_literal(s):
s = expand_path(s)
return pathlib.Path(s)
def regexsearch(s):
s = expand_path(s)
return reglob(s)
def globsearch(s):
csc = XSH.env.get("CASE_SENSITIVE_COMPLETIONS")
glob_sorted = XSH.env.get("GLOB_SORTED")
dotglob = XSH.env.get("DOTGLOB")
return globpath(
s,
ignore_case=(not csc),
return_empty=True,
sort_result=glob_sorted,
include_dotfiles=dotglob,
)
def pathsearch(func, s, pymode=False, pathobj=False):
"""
Takes a string and returns a list of file paths that match (regex, glob,
or arbitrary search function). If pathobj=True, the return is a list of
pathlib.Path objects instead of strings.
"""
if not callable(func) or len(inspect.signature(func).parameters) != 1:
error = "%r is not a known path search function"
raise XonshError(error % func)
o = func(s)
if pathobj and pymode:
o = list(map(pathlib.Path, o))
no_match = [] if pymode else [s]
return o if len(o) != 0 else no_match
def subproc_captured_stdout(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns the stdout
that was produced as a str.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="stdout", envs=envs)
def subproc_captured_inject(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns a list of
whitespace-separated strings of the stdout that was produced.
The string is split using xonsh's lexer, rather than Python's str.split()
or shlex.split().
"""
import xonsh.procs.specs
o = xonsh.procs.specs.run_subproc(cmds, captured="object", envs=envs)
o.end()
toks = []
for line in o:
line = line.rstrip(os.linesep)
toks.extend(XSH.execer.parser.lexer.split(line))
return toks
def subproc_captured_object(*cmds, envs=None):
"""
Runs a subprocess, capturing the output. Returns an instance of
CommandPipeline representing the completed command.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="object", envs=envs)
def subproc_captured_hiddenobject(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns an instance of
HiddenCommandPipeline representing the completed command.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="hiddenobject", envs=envs)
def subproc_uncaptured(*cmds, envs=None):
"""Runs a subprocess, without capturing the output. Returns the stdout
that was produced as a str.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured=False, envs=envs)
def ensure_list_of_strs(x):
"""Ensures that x is a list of strings."""
if isinstance(x, str):
rtn = [x]
elif isinstance(x, cabc.Sequence):
rtn = [i if isinstance(i, str) else str(i) for i in x]
else:
rtn = [str(x)]
return rtn
def ensure_str_or_callable(x):
"""Ensures that x is single string or function."""
if isinstance(x, str) or callable(x):
return x
if isinstance(x, bytes):
# ``os.fsdecode`` decodes using "surrogateescape" on linux and "strict" on windows.
# This is used to decode bytes for interfacing with the os, notably for command line arguments.
# See https://www.python.org/dev/peps/pep-0383/#specification
return os.fsdecode(x)
return str(x)
def list_of_strs_or_callables(x):
"""
Ensures that x is a list of strings or functions.
This is called when using the ``@()`` operator to expand it's content.
"""
if isinstance(x, (str, bytes)) or callable(x):
rtn = [ensure_str_or_callable(x)]
elif isinstance(x, cabc.Iterable):
rtn = list(map(ensure_str_or_callable, x))
else:
rtn = [ensure_str_or_callable(x)]
return rtn
def list_of_list_of_strs_outer_product(x):
"""Takes an outer product of a list of strings"""
lolos = map(ensure_list_of_strs, x)
rtn = []
for los in itertools.product(*lolos):
s = "".join(los)
if "*" in s:
rtn.extend(XSH.glob(s))
else:
rtn.append(XSH.expand_path(s))
return rtn
def eval_fstring_field(field):
"""Evaluates the argument in Xonsh context."""
res = XSH.execer.eval(
field[0].strip(), glbs=globals(), locs=XSH.ctx, filename=field[1]
)
return res
@lazyobject
def MACRO_FLAG_KINDS():
return {
"s": str,
"str": str,
"string": str,
"a": AST,
"ast": AST,
"c": types.CodeType,
"code": types.CodeType,
"compile": types.CodeType,
"v": eval,
"eval": eval,
"x": exec,
"exec": exec,
"t": type,
"type": type,
}
def _convert_kind_flag(x):
"""Puts a kind flag (string) a canonical form."""
x = x.lower()
kind = MACRO_FLAG_KINDS.get(x, None)
if kind is None:
raise TypeError(f"{x!r} not a recognized macro type.")
return kind
def convert_macro_arg(raw_arg, kind, glbs, locs, *, name="<arg>", macroname="<macro>"):
"""Converts a string macro argument based on the requested kind.
Parameters
----------
raw_arg : str
The str representation of the macro argument.
kind : object
A flag or type representing how to convert the argument.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
The locals from the call site.
name : str, optional
The macro argument name.
macroname : str, optional
The name of the macro itself.
Returns
-------
The converted argument.
"""
# munge kind and mode to start
mode = None
if isinstance(kind, cabc.Sequence) and not isinstance(kind, str):
# have (kind, mode) tuple
kind, mode = kind
if isinstance(kind, str):
kind = _convert_kind_flag(kind)
if kind is str or kind is None:
return raw_arg # short circuit since there is nothing else to do
# select from kind and convert
execer = XSH.execer
filename = macroname + "(" + name + ")"
if kind is AST:
ctx = set(dir(builtins)) | set(glbs.keys())
if locs is not None:
ctx |= set(locs.keys())
mode = mode or "eval"
if mode != "eval" and not raw_arg.endswith("\n"):
raw_arg += "\n"
arg = execer.parse(raw_arg, ctx, mode=mode, filename=filename)
elif kind is types.CodeType or kind is compile: # NOQA
mode = mode or "eval"
arg = execer.compile(
raw_arg, mode=mode, glbs=glbs, locs=locs, filename=filename
)
elif kind is eval:
arg = execer.eval(raw_arg, glbs=glbs, locs=locs, filename=filename)
elif kind is exec:
mode = mode or "exec"
if not raw_arg.endswith("\n"):
raw_arg += "\n"
arg = execer.exec(raw_arg, mode=mode, glbs=glbs, locs=locs, filename=filename)
elif kind is type:
arg = type(execer.eval(raw_arg, glbs=glbs, locs=locs, filename=filename))
else:
msg = "kind={0!r} and mode={1!r} was not recognized for macro " "argument {2!r}"
raise TypeError(msg.format(kind, mode, name))
return arg
@contextlib.contextmanager
def in_macro_call(f, glbs, locs):
"""Attaches macro globals and locals temporarily to function as a
context manager.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
The locals from the call site.
"""
prev_glbs = getattr(f, "macro_globals", None)
prev_locs = getattr(f, "macro_locals", None)
f.macro_globals = glbs
f.macro_locals = locs
yield
if prev_glbs is None:
del f.macro_globals
else:
f.macro_globals = prev_glbs
if prev_locs is None:
del f.macro_locals
else:
f.macro_locals = prev_locs
def call_macro(f, raw_args, glbs, locs):
"""Calls a function as a macro, returning its result.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
raw_args : tuple of str
The str representation of arguments of that were passed into the
macro. These strings will be parsed, compiled, evaled, or left as
a string depending on the annotations of f.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
The locals from the call site.
"""
sig = inspect.signature(f)
empty = inspect.Parameter.empty
macroname = f.__name__
i = 0
args = []
for (key, param), raw_arg in zip(sig.parameters.items(), raw_args):
i += 1
if raw_arg == "*":
break
kind = param.annotation
if kind is empty or kind is None:
kind = str
arg = convert_macro_arg(
raw_arg, kind, glbs, locs, name=key, macroname=macroname
)
args.append(arg)
reg_args, kwargs = _eval_regular_args(raw_args[i:], glbs, locs)
args += reg_args
with in_macro_call(f, glbs, locs):
rtn = f(*args, **kwargs)
return rtn
@lazyobject
def KWARG_RE():
return re.compile(r"([A-Za-z_]\w*=|\*\*)")
def _starts_as_arg(s):
"""Tests if a string starts as a non-kwarg string would."""
return KWARG_RE.match(s) is None
def _eval_regular_args(raw_args, glbs, locs):
if not raw_args:
return [], {}
arglist = list(itertools.takewhile(_starts_as_arg, raw_args))
kwarglist = raw_args[len(arglist) :]
execer = XSH.execer
if not arglist:
args = arglist
kwargstr = "dict({})".format(", ".join(kwarglist))
kwargs = execer.eval(kwargstr, glbs=glbs, locs=locs)
elif not kwarglist:
argstr = "({},)".format(", ".join(arglist))
args = execer.eval(argstr, glbs=glbs, locs=locs)
kwargs = {}
else:
argstr = "({},)".format(", ".join(arglist))
kwargstr = "dict({})".format(", ".join(kwarglist))
both = f"({argstr}, {kwargstr})"
args, kwargs = execer.eval(both, glbs=glbs, locs=locs)
return args, kwargs
def enter_macro(obj, raw_block, glbs, locs):
"""Prepares to enter a context manager macro by attaching the contents
of the macro block, globals, and locals to the object. These modifications
are made in-place and the original object is returned.
Parameters
----------
obj : context manager
The object that is about to be entered via a with-statement.
raw_block : str
The str of the block that is the context body.
This string will be parsed, compiled, evaled, or left as
a string depending on the return annotation of obj.__enter__.
glbs : Mapping
The globals from the context site.
locs : Mapping or None
The locals from the context site.
Returns
-------
obj : context manager
The same context manager but with the new macro information applied.
"""
# recurse down sequences
if isinstance(obj, cabc.Sequence):
for x in obj:
enter_macro(x, raw_block, glbs, locs)
return obj
# convert block as needed
kind = getattr(obj, "__xonsh_block__", str)
macroname = getattr(obj, "__name__", "<context>")
block = convert_macro_arg(
raw_block, kind, glbs, locs, name="<with!>", macroname=macroname
)
# attach attrs
obj.macro_globals = glbs
obj.macro_locals = locs
obj.macro_block = block
return obj
@contextlib.contextmanager
def xonsh_builtins(execer=None):
"""A context manager for using the xonsh builtins only in a limited
scope. Likely useful in testing.
"""
XSH.load(execer=execer)
yield
XSH.unload()
class XonshSession:
"""All components defining a xonsh session."""
def __init__(self):
self.execer = None
self.ctx = {}
self.builtins_loaded = False
self.history = None
self.shell = None
self.env = None
self.rc_files = None
# AST-invoked functions
self.help = helper
self.superhelp = superhelper
self.pathsearch = pathsearch
self.globsearch = globsearch
self.regexsearch = regexsearch
self.glob = globpath
self.expand_path = expand_path
self.subproc_captured_stdout = subproc_captured_stdout
self.subproc_captured_inject = subproc_captured_inject
self.subproc_captured_object = subproc_captured_object
self.subproc_captured_hiddenobject = subproc_captured_hiddenobject
self.subproc_uncaptured = subproc_uncaptured
self.call_macro = call_macro
self.enter_macro = enter_macro
self.path_literal = path_literal
self.list_of_strs_or_callables = list_of_strs_or_callables
self.list_of_list_of_strs_outer_product = list_of_list_of_strs_outer_product
self.eval_fstring_field = eval_fstring_field
# Session attributes
self.exit = None
self.stdout_uncaptured = None
self.stderr_uncaptured = None
self._py_exit = None
self._py_quit = None
self.commands_cache = None
self.modules_cache = None
self.all_jobs = None
self.completers = None
self.builtins = None
self._initial_builtin_names = None
@property
def aliases(self):
if self.commands_cache is None:
return
return self.commands_cache.aliases
def _disable_python_exit(self):
# Disable Python interactive quit/exit
if hasattr(builtins, "exit"):
self._py_exit = builtins.exit
del builtins.exit
if hasattr(builtins, "quit"):
self._py_quit = builtins.quit
del builtins.quit
def _restore_python_exit(self):
if self._py_exit is not None:
builtins.exit = self._py_exit
if self._py_quit is not None:
builtins.quit = self._py_quit
def load(self, execer=None, ctx=None, **kwargs):
"""Loads the session with default values.
Parameters
----------
execer : Execer, optional
Xonsh execution object, may be None to start
ctx : Mapping, optional
Context to start xonsh session with.
"""
from xonsh.commands_cache import CommandsCache
from xonsh.completers.init import default_completers
from xonsh.environ import Env, default_env
if not hasattr(builtins, "__xonsh__"):
builtins.__xonsh__ = self
if ctx is not None:
self.ctx = ctx
self.env = kwargs.pop("env") if "env" in kwargs else Env(default_env())
self.exit = False
self.stdout_uncaptured = None
self.stderr_uncaptured = None
self._disable_python_exit()
self.execer = execer
self.modules_cache = {}
self.all_jobs = {}
self.builtins = get_default_builtins(execer)
self._initial_builtin_names = frozenset(vars(self.builtins))
aliases_given = kwargs.pop("aliases", None)
for attr, value in kwargs.items():
if hasattr(self, attr):
setattr(self, attr, value)
self.commands_cache = (
kwargs.pop("commands_cache")
if "commands_cache" in kwargs
else CommandsCache(self.env, aliases_given)
)
self.link_builtins()
self.builtins_loaded = True
self.completers = default_completers(self.commands_cache)
def flush_on_exit(s=None, f=None):
if self.history is not None:
self.history.flush(at_exit=True)
atexit.register(flush_on_exit)
# Add one-shot handler for exit
for sig in AT_EXIT_SIGNALS:
resetting_signal_handle(sig, flush_on_exit)
def link_builtins(self):
# public built-ins
for refname in self._initial_builtin_names:
objname = f"__xonsh__.builtins.{refname}"
proxy = DynamicAccessProxy(refname, objname)
setattr(builtins, refname, proxy)
# sneak the path search functions into the aliases
# Need this inline/lazy import here since we use locate_binary that
# relies on __xonsh__.env in default aliases
builtins.default_aliases = builtins.aliases = self.aliases
def unlink_builtins(self):
for name in self._initial_builtin_names:
if hasattr(builtins, name):
delattr(builtins, name)
def unload(self):
if not hasattr(builtins, "__xonsh__"):
self.builtins_loaded = False
return
if hasattr(self.env, "undo_replace_env"):
self.env.undo_replace_env()
self._restore_python_exit()
if not self.builtins_loaded:
return
self.unlink_builtins()
delattr(builtins, "__xonsh__")
self.builtins_loaded = False
def get_default_builtins(execer=None):
from xonsh.events import events
return types.SimpleNamespace(
XonshError=XonshError,
XonshCalledProcessError=XonshCalledProcessError,
evalx=None if execer is None else execer.eval,
execx=None if execer is None else execer.exec,
compilex=None if execer is None else execer.compile,
events=events,
print_color=print_color,
printx=print_color,
)
class DynamicAccessProxy:
"""Proxies access dynamically."""
def __init__(self, refname, objname):
"""
Parameters
----------
refname : str
'.'-separated string that represents the new, reference name that
the user will access.
objname : str
'.'-separated string that represents the name where the target
object actually lives that refname points to.
"""
super().__setattr__("refname", refname)
super().__setattr__("objname", objname)
@property
def obj(self):
"""Dynamically grabs object"""
names = self.objname.split(".")
obj = builtins
for name in names:
obj = getattr(obj, name)
return obj
def __getattr__(self, name):
return getattr(self.obj, name)
def __setattr__(self, name, value):
return super().__setattr__(self.obj, name, value)
def __delattr__(self, name):
return delattr(self.obj, name)
def __getitem__(self, item):
return self.obj.__getitem__(item)
def __setitem__(self, item, value):
return self.obj.__setitem__(item, value)
def __delitem__(self, item):
del self.obj[item]
def __call__(self, *args, **kwargs):
return self.obj.__call__(*args, **kwargs)
def __dir__(self):
return self.obj.__dir__()
# singleton
XSH = XonshSession()