Repository navigation
Expand file tree
/
Copy pathbase_shell.py
More file actions
229 lines (196 loc) · 6.77 KB
/
Copy pathbase_shell.py
File metadata and controls
229 lines (196 loc) · 6.77 KB
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
"""The base class for xonsh shell"""
import io
import os
import shlex
import sys
import time
import builtins
import traceback
from xonsh.execer import Execer
from xonsh.tools import XonshError, escape_windows_title_string, ON_WINDOWS, \
print_exception
from xonsh.completer import Completer
from xonsh.environ import multiline_prompt, format_prompt
class TeeOut(object):
"""Tees stdout into the original sys.stdout and another buffer instance that is
provided.
"""
def __init__(self, buf, *args, **kwargs):
self.buffer = buf
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
def close(self):
"""Restores the original stdout."""
sys.stdout = self.stdout
def write(self, data):
"""Writes data to the original stdout and the buffer."""
self.stdout.write(data)
self.buffer.write(data)
def flush(self):
"""Flushes both the original stdout and the buffer."""
self.stdout.flush()
self.buffer.flush()
class TeeErr(object):
"""Tees stderr into the original sys.stdout and another buffer instance that is
provided.
"""
def __init__(self, buf, *args, **kwargs):
self.buffer = buf
self.stderr = sys.stderr
sys.stderr = self
def __del__(self):
sys.stderr = self.stderr
def close(self):
"""Restores the original stderr."""
sys.stderr = self.stderr
def write(self, data):
"""Writes data to the original stderr and the buffer."""
self.stderr.write(data)
self.buffer.write(data)
def flush(self):
"""Flushes both the original stderr and the buffer."""
self.stderr.flush()
self.buffer.flush()
class Tee(io.StringIO):
"""Class that merges tee'd stdout and stderr into a single buffer, namely itself.
This represents what a user would actually see on the command line.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.stdout = TeeOut(self)
self.stderr = TeeErr(self)
def __del__(self):
del self.stdout, self.stderr
super().__del__()
def close(self):
"""Closes the buffer as well as the stdout and stderr tees."""
self.stdout.close()
self.stderr.close()
super().close()
class BaseShell(object):
"""The xonsh shell."""
def __init__(self, execer, ctx, **kwargs):
super().__init__(**kwargs)
self.execer = execer
self.ctx = ctx
self.completer = Completer()
self.buffer = []
self.need_more_lines = False
self.mlprompt = None
self.gitsome = None
def emptyline(self):
"""Called when an empty line has been entered."""
self.need_more_lines = False
self.default('')
def precmd(self, line):
"""Called just before execution of line."""
return line if self.need_more_lines else line.lstrip()
def default(self, line):
"""Implements code execution."""
line = line if line.endswith('\n') else line + '\n'
src, code = self.push(line)
if code is None:
return
hist = builtins.__xonsh_history__
ts1 = None
tee = Tee() if builtins.__xonsh_env__.get('XONSH_STORE_STDOUT') \
else io.StringIO()
try:
ts0 = time.time()
self.execer.exec(code, mode='single', glbs=self.ctx) # no locals
ts1 = time.time()
if hist.last_cmd_rtn is None:
hist.last_cmd_rtn = 0 # returncode for success
except XonshError as e:
print(e.args[0], file=sys.stderr)
if hist.last_cmd_rtn is None:
hist.last_cmd_rtn = 1 # return code for failure
except Exception:
print_exception()
if hist.last_cmd_rtn is None:
hist.last_cmd_rtn = 1 # return code for failure
finally:
ts1 = ts1 or time.time()
self._append_history(inp=src, ts=[ts0, ts1], tee_out=tee.getvalue())
tee.close()
if builtins.__xonsh_exit__:
return True
def push(self, line):
"""Pushes a line onto the buffer and compiles the code in a way that
enables multiline input.
"""
code = None
self.buffer.append(line)
if self.need_more_lines:
return None, code
src = ''.join(self.buffer)
try:
code = self.execer.compile(src,
mode='single',
glbs=None,
locs=self.ctx)
self.reset_buffer()
except SyntaxError:
if line == '\n':
self.reset_buffer()
print_exception()
return src, None
self.need_more_lines = True
except Exception:
self.reset_buffer()
print_exception()
return src, None
return src, code
def reset_buffer(self):
"""Resets the line buffer."""
self.buffer.clear()
self.need_more_lines = False
self.mlprompt = None
def settitle(self):
"""Sets terminal title."""
env = builtins.__xonsh_env__
term = env.get('TERM', None)
if term is None or term == 'linux':
return
t = 'gitsome'
if ON_WINDOWS and 'ANSICON' not in env:
t = escape_windows_title_string(t)
os.system('title {}'.format(t))
else:
sys.stdout.write("\x1b]2;{0}\x07".format(t))
@property
def prompt(self):
"""Obtains the current prompt string."""
if self.need_more_lines:
if self.mlprompt is None:
try:
self.mlprompt = multiline_prompt()
except Exception:
print_exception()
self.mlprompt = '<multiline prompt error> '
return self.mlprompt
env = builtins.__xonsh_env__
p = env.get('PROMPT')
try:
p = format_prompt(p)
except Exception:
print_exception()
self.settitle()
return p
def _append_history(self, tee_out=None, **info):
hist = builtins.__xonsh_history__
info['rtn'] = hist.last_cmd_rtn
tee_out = tee_out or None
last_out = hist.last_cmd_out or None
if last_out is None and tee_out is None:
pass
elif last_out is None and tee_out is not None:
info['out'] = tee_out
elif last_out is not None and tee_out is None:
info['out'] = last_out
else:
info['out'] = tee_out + '\n' + last_out
hist.append(info)
hist.last_cmd_rtn = hist.last_cmd_out = None