Skip to content

Commit

Permalink
[oil-language] Implement read --all
Browse files Browse the repository at this point in the history
Addresses issue #711.
  • Loading branch information
Andy Chu committed Oct 11, 2020
1 parent d9d468e commit 0ee831d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
44 changes: 39 additions & 5 deletions osh/builtin_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,7 @@ def ReadLineFromStdin(delim_char):

def _ReadLine():
# type: () -> str
"""Read a line from stdin.
TODO: use a more efficient function in C
"""
"""Read a line from stdin."""
# TODO: This should be an array of integers in C++
chars = [] # type: List[str]
while True:
Expand All @@ -181,6 +178,20 @@ def _ReadLine():
return ''.join(chars)


def _ReadAll():
# type: () -> str
"""Read all of stdin."""
chunks = [] # type: List[str]
while True:
c = posix.read(0, 4096)
if len(c) == 0:
break

chunks.append(c)

return ''.join(chunks)


class Read(vm._Builtin):
def __init__(self, splitter, mem):
# type: (SplitContext, Mem) -> None
Expand All @@ -204,6 +215,16 @@ def _Line(self, arg, var_name):
self.mem.SetVar(lhs, value.Str(line), scope_e.LocalOnly)
return 0

def _All(self, var_name):
# type: (str) -> int
contents = _ReadAll()

# No error conditions?

lhs = lvalue.Named(var_name)
self.mem.SetVar(lhs, value.Str(contents), scope_e.LocalOnly)
return 0

def Run(self, cmd_val):
# type: (cmd_value__Argv) -> int
attrs, arg_r = flag_spec.ParseCmdVal('read', cmd_val)
Expand All @@ -227,7 +248,20 @@ def Run(self, cmd_val):
return self._Line(arg, var_name)

if arg.all:
e_usage('--all not implemented yet')
var_name, var_spid = arg_r.Peek2()
if var_name is None:
var_name = '_all'
else:
if var_name.startswith(':'): # optional : sigil
var_name = var_name[1:]
arg_r.Next()

next_arg, next_spid = arg_r.Peek2()
if next_arg is not None:
raise error.Usage('got extra argument', span_id=next_spid)

return self._All(var_name)

if arg.q:
e_usage('--qsn not implemented yet')

Expand Down
15 changes: 15 additions & 0 deletions spec/oil-builtins.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@ line=a
line=b
## END

#### read --all
echo foo | read --all
echo "[$_all]"

echo bad > tmp.txt
read --all :x < tmp.txt
echo "[$x]"

## STDOUT:
[foo
]
[bad
]
## END


#### shopt supports long flags
shopt -p nullglob
Expand Down

0 comments on commit 0ee831d

Please sign in to comment.