Skip to content

Commit

Permalink
Merge pull request #63 from Crestwave/getline
Browse files Browse the repository at this point in the history
Add support for getline < "-" and print > "-"
  • Loading branch information
benhoyt committed Aug 29, 2021
2 parents 9eb663f + ccaa0bc commit 0eb3f8c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
5 changes: 5 additions & 0 deletions interp/interp_test.go
Expand Up @@ -591,6 +591,11 @@ BEGIN { foo(5); bar(10) }
// {`BEGIN { ">&2 echo error" | getline; print }`, "", "error\n\n", "", ""},
{`BEGIN { print getline x < "/no/such/file" } # !fuzz`, "", "-1\n", "", ""},

// Redirecting to or from a filename of "-" means write to stdout or read from stdin
{`BEGIN { print getline x < "-"; print x }`, "a\nb\n", "1\na\n", "", ""},
{`{ print $0; print getline x <"-"; print x }`, "one\ntwo\n", "one\n0\n\ntwo\n0\n\n", "", ""},
{`BEGIN { print "x" >"-"; print "y" >"-" }`, "", "x\ny\n", "", ""},

// fflush() function - tests parsing and some edge cases, but not
// actual flushing behavior (that's partially tested in TestFlushes).
{`BEGIN { print fflush(); print fflush("") }`, "", "0\n0\n", "", ""},
Expand Down
13 changes: 13 additions & 0 deletions interp/io.go
Expand Up @@ -69,6 +69,10 @@ func (p *interp) getOutputStream(redirect Token, dest Expr) (io.Writer, error) {

switch redirect {
case GREATER, APPEND:
if name == "-" {
// filename of "-" means write to stdout, eg: print "x" >"-"
return p.output, nil
}
// Write or append to file
if p.noFileWrites {
return nil, newError("can't write to file due to NoFileWrites")
Expand Down Expand Up @@ -123,6 +127,15 @@ func (p *interp) getInputScannerFile(name string) (*bufio.Scanner, error) {
if _, ok := p.inputStreams[name]; ok {
return p.scanners[name], nil
}
if name == "-" {
// filename of "-" means read from stdin, eg: getline <"-"
if scanner, ok := p.scanners["-"]; ok {
return scanner, nil
}
scanner := p.newScanner(p.stdin)
p.scanners[name] = scanner
return scanner, nil
}
if p.noFileReads {
return nil, newError("can't read from file due to NoFileReads")
}
Expand Down

0 comments on commit 0eb3f8c

Please sign in to comment.