Skip to content

Commit

Permalink
interp: have a custom /dev/null implementation
Browse files Browse the repository at this point in the history
This fix reading and writing to /dev/null on Windows, where this file is
not available.

It may also add a very minimal performance improvement on other
plataforms, since now interp don't need to open and redirect to a real
file anymore.

Reference: #141
  • Loading branch information
andreynering authored and mvdan committed Jul 29, 2017
1 parent d002e24 commit b19ade2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
21 changes: 21 additions & 0 deletions interp/dev.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package interp

import (
"io"
)

var _ io.ReadWriteCloser = devNull{}

type devNull struct{}

func (devNull) Read(_ []byte) (int, error) {
return 0, io.EOF
}

func (devNull) Write(p []byte) (int, error) {
return len(p), nil
}

func (devNull) Close() error {
return nil
}
15 changes: 11 additions & 4 deletions interp/interp.go
Original file line number Diff line number Diff line change
Expand Up @@ -671,10 +671,17 @@ func (r *Runner) redir(rd *syntax.Redirect) (io.Closer, error) {
case syntax.RdrOut, syntax.RdrAll:
mode = os.O_RDWR | os.O_CREATE | os.O_TRUNC
}
f, err := os.OpenFile(r.relPath(arg), mode, 0644)
if err != nil {
// TODO: print to stderr?
return nil, err
var f io.ReadWriteCloser
switch arg {
case "/dev/null":
f = devNull{}
default:
var err error
f, err = os.OpenFile(r.relPath(arg), mode, 0644)
if err != nil {
// TODO: print to stderr?
return nil, err
}
}
switch rd.Op {
case syntax.RdrIn:
Expand Down
4 changes: 4 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,10 @@ var fileCases = []struct {
"mkdir a; touch a/b.x; echo */*.x; cd a; echo *.x",
"a/b.x\nb.x\n",
},

// /dev/null
{"echo foo >/dev/null", ""},
{"cat </dev/null", ""},
}

// concBuffer wraps a bytes.Buffer in a mutex so that concurrent writes
Expand Down

0 comments on commit b19ade2

Please sign in to comment.