-
Notifications
You must be signed in to change notification settings - Fork 67
/
file.go
55 lines (50 loc) · 1.43 KB
/
file.go
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
package emitter
import (
"context"
"io"
"os"
"github.com/brimdata/zed/pkg/bufwriter"
"github.com/brimdata/zed/pkg/storage"
"github.com/brimdata/zed/pkg/terminal"
"github.com/brimdata/zed/zio"
"github.com/brimdata/zed/zio/anyio"
)
func NewFileFromPath(ctx context.Context, engine storage.Engine, path string, unbuffered bool, opts anyio.WriterOpts) (zio.WriteCloser, error) {
if path == "" {
path = "stdio:stdout"
}
uri, err := storage.ParseURI(path)
if err != nil {
return nil, err
}
return NewFileFromURI(ctx, engine, uri, unbuffered, opts)
}
func IsTerminal(w io.Writer) bool {
if f, ok := w.(*os.File); ok {
return terminal.IsTerminalFile(f)
}
if nc, ok := w.(*storage.NopCloser); ok {
return IsTerminal(nc.Writer)
}
return false
}
func NewFileFromURI(ctx context.Context, engine storage.Engine, path *storage.URI, unbuffered bool, opts anyio.WriterOpts) (zio.WriteCloser, error) {
f, err := engine.Put(ctx, path)
if err != nil {
return nil, err
}
wc := io.WriteCloser(f)
if path.Scheme == "stdio" {
// Don't close stdio in case we live inside something
// that has multiple stdio users.
wc = zio.NopCloser(f)
}
if !unbuffered && !IsTerminal(f) {
// Don't buffer terminal output.
wc = bufwriter.New(wc)
}
// On close, zio.WriteCloser.Close will close and flush the
// downstream writer, which will flush the bufwriter here and,
// in turn, close its underlying writer.
return anyio.NewWriter(wc, opts)
}