OILS / builtin / read_osh.py View on Github | oils.pub

537 lines, 312 significant
1from __future__ import print_function
2
3from errno import EINTR
4
5from _devbuild.gen import arg_types
6from _devbuild.gen.runtime_asdl import (span_e, cmd_value)
7from _devbuild.gen.syntax_asdl import source, loc_t
8from _devbuild.gen.value_asdl import value, LeftName
9from core import alloc
10from core import error
11from core.error import e_die
12from core import pyos
13from core import pyutil
14from core import state
15from display import ui
16from core import vm
17from frontend import flag_util
18from frontend import reader
19from frontend import typed_args
20from mycpp import mops
21from mycpp import mylib
22from mycpp.mylib import log, STDIN_FILENO
23
24import posix_ as posix
25
26from typing import Tuple, List, Any, TYPE_CHECKING
27if TYPE_CHECKING:
28 from _devbuild.gen.runtime_asdl import span_t
29 from frontend.parse_lib import ParseContext
30 from frontend import args
31 from osh.cmd_eval import CommandEvaluator
32 from osh.split import SplitContext
33
34_ = log
35
36# The read builtin splits using IFS.
37#
38# Summary:
39# - Split with IFS, except \ can escape them! This is different than the
40# algorithm for splitting words (at least the way I've represented it.)
41
42# Bash manual:
43# - If there are more words than names, the remaining words and their
44# intervening delimiters are assigned to the last name.
45# - If there are fewer words read from the input stream than names, the
46# remaining names are assigned empty values.
47# - The characters in the value of the IFS variable are used to split the line
48# into words using the same rules the shell uses for expansion (described
49# above in Word Splitting).
50# - The backslash character '\' may be used to remove any special meaning for
51# the next character read and for line continuation.
52
53
54def _AppendParts(
55 s, # type: str
56 spans, # type: List[Tuple[span_t, int]]
57 max_results, # type: int
58 join_next, # type: bool
59 parts, # type: List[mylib.BufWriter]
60):
61 # type: (...) -> Tuple[bool, bool]
62 """Append to 'parts', for the 'read' builtin.
63
64 Similar to _SpansToParts in osh/split.py
65
66 Args:
67 s: The original string
68 spans: List of (span, end_index)
69 max_results: the maximum number of parts we want
70 join_next: Whether to join the next span to the previous part. This
71 happens in two cases:
72 - when we have '\ '
73 - and when we have more spans # than max_results.
74 """
75 start_index = 0
76 # If the last span was black, and we get a backslash, set join_next to merge
77 # two black spans.
78 last_span_was_black = False
79
80 for span_type, end_index in spans:
81 if span_type == span_e.Black:
82 if join_next and len(parts):
83 parts[-1].write(s[start_index:end_index])
84 join_next = False
85 else:
86 buf = mylib.BufWriter()
87 buf.write(s[start_index:end_index])
88 parts.append(buf)
89 last_span_was_black = True
90
91 elif span_type == span_e.Delim:
92 if join_next:
93 parts[-1].write(s[start_index:end_index])
94 join_next = False
95 last_span_was_black = False
96
97 elif span_type == span_e.Backslash:
98 if last_span_was_black:
99 join_next = True
100 last_span_was_black = False
101
102 if max_results and len(parts) >= max_results:
103 join_next = True
104
105 start_index = end_index
106
107 done = True
108 if len(spans):
109 #log('%s %s', s, spans)
110 #log('%s', spans[-1])
111 last_span_type, _ = spans[-1]
112 if last_span_type == span_e.Backslash:
113 done = False
114
115 #log('PARTS %s', parts)
116 return done, join_next
117
118
119#
120# Three read() wrappers for 'read' builtin that RunPendingTraps: _ReadN,
121# _ReadPortion, and ReadLineSlowly
122#
123
124
125def _ReadN(num_bytes, cmd_ev):
126 # type: (int, CommandEvaluator) -> str
127 chunks = [] # type: List[str]
128 bytes_left = num_bytes
129 while bytes_left > 0:
130 n, err_num = pyos.Read(STDIN_FILENO, bytes_left,
131 chunks) # read up to n bytes
132
133 if n < 0:
134 if err_num == EINTR:
135 cmd_ev.RunPendingTraps()
136 # retry after running traps
137 else:
138 raise pyos.ReadError(err_num)
139
140 elif n == 0: # EOF
141 break
142
143 else:
144 bytes_left -= n
145
146 return ''.join(chunks)
147
148
149def _ReadPortion(delim_byte, max_chars, cmd_ev):
150 # type: (int, int, CommandEvaluator) -> Tuple[str, bool]
151 """Read a portion of stdin.
152
153 Reads until delimiter or max_chars, which ever comes first. Will ignore
154 max_chars if it's set to -1.
155
156 The delimiter is not included in the result.
157 """
158 ch_array = [] # type: List[int]
159 eof = False
160
161 bytes_read = 0
162 while True:
163 if max_chars >= 0 and bytes_read >= max_chars:
164 break
165
166 ch, err_num = pyos.ReadByte(0)
167 if ch < 0:
168 if err_num == EINTR:
169 cmd_ev.RunPendingTraps()
170 # retry after running traps
171 else:
172 raise pyos.ReadError(err_num)
173
174 elif ch == pyos.EOF_SENTINEL:
175 eof = True
176 break
177
178 elif ch == delim_byte:
179 break
180
181 elif ch == 0:
182 # Quirk of most shells except zsh: they ignore NUL bytes!
183 pass
184
185 else:
186 ch_array.append(ch)
187
188 bytes_read += 1
189
190 return pyutil.ChArrayToString(ch_array), eof
191
192
193def ReadLineSlowly(cmd_ev, with_eol=True):
194 # type: (CommandEvaluator, bool) -> Tuple[str, bool]
195 """Read a line from stdin, unbuffered
196
197 Used by mapfile and read --raw-line.
198
199 sys.stdin.readline() in Python has its own buffering which is incompatible
200 with shell semantics. dash, mksh, and zsh all read a single byte at a time
201 with read(0, 1).
202 """
203 ch_array = [] # type: List[int]
204 eof = False
205 is_first_byte = True
206 while True:
207 ch, err_num = pyos.ReadByte(0)
208 #log(' ch %d', ch)
209
210 if ch < 0:
211 if err_num == EINTR:
212 cmd_ev.RunPendingTraps()
213 # retry after running traps
214 else:
215 raise pyos.ReadError(err_num)
216
217 elif ch == pyos.EOF_SENTINEL:
218 if is_first_byte:
219 eof = True
220 break
221
222 elif ch == pyos.NEWLINE_CH:
223 if with_eol:
224 ch_array.append(ch)
225 break
226
227 else:
228 ch_array.append(ch)
229
230 is_first_byte = False
231
232 return pyutil.ChArrayToString(ch_array), eof
233
234
235def ReadAll():
236 # type: () -> str
237 """Read all of stdin.
238
239 Similar to command sub in core/executor.py.
240 """
241 chunks = [] # type: List[str]
242 while True:
243 n, err_num = pyos.Read(0, 4096, chunks)
244
245 if n < 0:
246 if err_num == EINTR:
247 # Retry only. Like read --line (and command sub), read --all
248 # doesn't run traps. It would be a bit weird to run every 4096
249 # bytes.
250 pass
251 else:
252 raise pyos.ReadError(err_num)
253
254 elif n == 0: # EOF
255 break
256
257 return ''.join(chunks)
258
259
260class ctx_TermAttrs(object):
261
262 def __init__(self, fd, local_modes):
263 # type: (int, int) -> None
264 self.fd = fd
265
266 # We change term_attrs[3] in Python, which is lflag "local modes"
267 self.orig_local_modes, self.term_attrs = pyos.PushTermAttrs(
268 fd, local_modes)
269
270 def __enter__(self):
271 # type: () -> None
272 pass
273
274 def __exit__(self, type, value, traceback):
275 # type: (Any, Any, Any) -> None
276 pyos.PopTermAttrs(self.fd, self.orig_local_modes, self.term_attrs)
277
278
279class Read(vm._Builtin):
280
281 def __init__(
282 self,
283 splitter, # type: SplitContext
284 mem, # type: state.Mem
285 parse_ctx, # type: ParseContext
286 cmd_ev, # type: CommandEvaluator
287 errfmt, # type: ui.ErrorFormatter
288 ):
289 # type: (...) -> None
290 self.splitter = splitter
291 self.mem = mem
292 self.parse_ctx = parse_ctx
293 self.cmd_ev = cmd_ev
294 self.errfmt = errfmt
295 self.stdin_ = mylib.Stdin()
296
297 # Was --qsn, might be restored as --j8-word or --j8-line
298 if 0:
299 #from data_lang import qsn_native
300 def _MaybeDecodeLine(self, line):
301 # type: (str) -> str
302 """Raises error.Parse if line isn't valid."""
303
304 # Lines that don't start with a single quote aren't QSN. They may
305 # contain a single quote internally, like:
306 #
307 # Fool's Gold
308 if not line.startswith("'"):
309 return line
310
311 arena = self.parse_ctx.arena
312 line_reader = reader.StringLineReader(line, arena)
313 lexer = self.parse_ctx.MakeLexer(line_reader)
314
315 # The parser only yields valid tokens:
316 # Char_OneChar, Char_Hex, Char_UBraced
317 # So we can use word_compile.EvalCStringToken, which is also used for
318 # $''.
319 # Important: we don't generate Id.Unknown_Backslash because that is valid
320 # in echo -e. We just make it Id.Unknown_Tok?
321
322 # TODO: read location info should know about stdin, and redirects, and
323 # pipelines?
324 with alloc.ctx_SourceCode(arena, source.Stdin('')):
325 #tokens = qsn_native.Parse(lexer)
326 pass
327 #tmp = [word_compile.EvalCStringToken(t) for t in tokens]
328 #return ''.join(tmp)
329 return ''
330
331 def Run(self, cmd_val):
332 # type: (cmd_value.Argv) -> int
333 try:
334 status = self._Run(cmd_val)
335 except pyos.ReadError as e: # different paths for read -d, etc.
336 # don't quote code since YSH errexit will likely quote
337 self.errfmt.PrintMessage("Oils read error: %s" %
338 posix.strerror(e.err_num))
339 status = 1
340 except (IOError, OSError) as e: # different paths for read -d, etc.
341 self.errfmt.PrintMessage("Oils read I/O error: %s" %
342 pyutil.strerror(e))
343 status = 1
344 return status
345
346 def _ReadYsh(self, arg, arg_r, cmd_val):
347 # type: (arg_types.read, args.Reader, cmd_value.Argv) -> int
348 """
349 Usage:
350
351 read --all # sets _reply
352 read --all (&x) # sets x
353
354 Invalid for now:
355
356 read (&x) # YSH doesn't have token splitting
357 # we probably want read --row too
358 """
359 place = None # type: value.Place
360
361 if cmd_val.proc_args: # read --flag (&x)
362 rd = typed_args.ReaderForProc(cmd_val)
363 place = rd.PosPlace()
364 rd.Done()
365
366 blame_loc = cmd_val.proc_args.typed_args.left # type: loc_t
367
368 else: # read --flag
369 var_name = '_reply'
370
371 #log('VAR %s', var_name)
372 blame_loc = cmd_val.arg_locs[0]
373 place = value.Place(LeftName(var_name, blame_loc),
374 self.mem.CurrentFrame())
375
376 next_arg, next_loc = arg_r.Peek2()
377 if next_arg is not None:
378 raise error.Usage('got extra argument', next_loc)
379
380 num_bytes = mops.BigTruncate(arg.num_bytes)
381 if num_bytes != -1: # read --num-bytes
382 contents = _ReadN(num_bytes, self.cmd_ev)
383 status = 0
384
385 elif arg.raw_line: # read --raw-line is unbuffered
386 contents, eof = ReadLineSlowly(self.cmd_ev, with_eol=arg.with_eol)
387 #log('EOF %s', eof)
388 #status = 1 if eof else 0
389 status = 1 if eof else 0
390
391 elif arg.all: # read --all
392 contents = ReadAll()
393 status = 0
394
395 else:
396 raise AssertionError()
397
398 self.mem.SetPlace(place, value.Str(contents), blame_loc)
399 return status
400
401 def _Run(self, cmd_val):
402 # type: (cmd_value.Argv) -> int
403 attrs, arg_r = flag_util.ParseCmdVal('read',
404 cmd_val,
405 accept_typed_args=True)
406 arg = arg_types.read(attrs.attrs)
407 names = arg_r.Rest()
408
409 if arg.u != mops.MINUS_ONE:
410 # TODO: could implement this
411 raise error.Usage('-u flag not implemented', cmd_val.arg_locs[0])
412
413 if arg.raw_line or arg.all or mops.BigTruncate(arg.num_bytes) != -1:
414 return self._ReadYsh(arg, arg_r, cmd_val)
415
416 if cmd_val.proc_args:
417 raise error.Usage(
418 "doesn't accept typed args without --all, or --num-bytes",
419 cmd_val.proc_args.typed_args.left)
420
421 if arg.t >= 0.0:
422 if arg.t != 0.0:
423 e_die("read -t isn't implemented (except t=0)")
424 else:
425 return 0 if pyos.InputAvailable(STDIN_FILENO) else 1
426
427 bits = 0
428 if self.stdin_.isatty():
429 # -d and -n should be unbuffered
430 if arg.d is not None or mops.BigTruncate(arg.n) >= 0:
431 bits |= pyos.TERM_ICANON
432 if arg.s: # silent
433 bits |= pyos.TERM_ECHO
434
435 if arg.p is not None: # only if tty
436 mylib.Stderr().write(arg.p)
437
438 if bits == 0:
439 status = self._Read(arg, names)
440 else:
441 with ctx_TermAttrs(STDIN_FILENO, ~bits):
442 status = self._Read(arg, names)
443 return status
444
445 def _Read(self, arg, names):
446 # type: (arg_types.read, List[str]) -> int
447
448 # read a certain number of bytes, NOT respecting delimiter (-1 means
449 # unset)
450 arg_N = mops.BigTruncate(arg.N)
451 if arg_N >= 0:
452 s = _ReadN(arg_N, self.cmd_ev)
453
454 if len(names):
455 name = names[0] # ignore other names
456
457 # Clear extra names, as bash does
458 for i in xrange(1, len(names)):
459 state.BuiltinSetString(self.mem, names[i], '')
460 else:
461 name = 'REPLY' # default variable name
462
463 state.BuiltinSetString(self.mem, name, s)
464
465 # Did we read all the bytes we wanted?
466 return 0 if len(s) == arg_N else 1
467
468 do_split = False
469
470 if len(names):
471 do_split = True # read myvar does word splitting
472 else:
473 # read without args does NOT split, and fills in $REPLY
474 names.append('REPLY')
475
476 if arg.a is not None:
477 max_results = 0 # array can hold all parts
478 do_split = True
479 else:
480 # Assign one part to each variable name; leftovers are assigned to
481 # the last name
482 max_results = len(names)
483
484 if arg.Z: # -0 is synonym for IFS= read -r -d ''
485 do_split = False
486 raw = True
487 delim_byte = 0
488 else:
489 raw = arg.r
490 if arg.d is not None:
491 if len(arg.d):
492 delim_byte = ord(arg.d[0])
493 else:
494 delim_byte = 0 # -d '' delimits by NUL
495 else:
496 delim_byte = pyos.NEWLINE_CH # read a line
497
498 # Read MORE THAN ONE line for \ line continuation (and not read -r)
499 parts = [] # type: List[mylib.BufWriter]
500 join_next = False
501 status = 0
502 while True:
503 chunk, eof = _ReadPortion(delim_byte, mops.BigTruncate(arg.n),
504 self.cmd_ev)
505
506 if eof:
507 # status 1 to terminate loop. (This is true even though we set
508 # variables).
509 status = 1
510
511 #log('LINE %r', chunk)
512 if len(chunk) == 0:
513 break
514
515 spans = self.splitter.SplitForRead(chunk, not raw, do_split)
516 done, join_next = _AppendParts(chunk, spans, max_results,
517 join_next, parts)
518
519 #log('PARTS %s continued %s', parts, continued)
520 if done:
521 break
522
523 entries = [buf.getvalue() for buf in parts]
524 num_parts = len(entries)
525 if arg.a is not None:
526 state.BuiltinSetArray(self.mem, arg.a, entries)
527 else:
528 for i in xrange(max_results):
529 if i < num_parts:
530 s = entries[i]
531 else:
532 s = '' # if there are too many variables
533 var_name = names[i]
534 #log('read: %s = %s', var_name, s)
535 state.BuiltinSetString(self.mem, var_name, s)
536
537 return status