-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
95 lines (78 loc) · 1.74 KB
/
writer.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2020 murosan. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gollect
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/atotto/clipboard"
)
type writer struct {
io.Writer
buf bytes.Buffer
provider writerProvider
config *Config
}
func (w *writer) Write(p []byte) (n int, err error) {
return w.buf.Write(p)
}
func (w *writer) writeForeach() error {
for _, out := range w.config.OutputPaths {
wr := w.provider.provide(out)
if _, err := wr.Write(w.buf.Bytes()); err != nil {
return fmt.Errorf("write: %w", err)
}
}
if w.config.output != nil {
// for test
w.config.output.Write(w.buf.Bytes())
}
return nil
}
type stdoutWriter struct{ io.Writer }
func (w *stdoutWriter) Write(p []byte) (int, error) {
f := os.Stdout
defer closer(f)
return f.Write(p)
}
type clipboardWriter struct{ io.Writer }
func (w *clipboardWriter) Write(p []byte) (int, error) {
if clipboard.Unsupported {
return 0, errors.New("no support for clipboard")
}
return len(p), clipboard.WriteAll(string(p))
}
type fileWriter struct {
io.Writer
path string
}
func (w *fileWriter) Write(p []byte) (int, error) {
file, err := os.Create(w.path)
if err != nil {
return 0, err
}
defer closer(file)
return file.WriteAt(p, 0)
}
// io.Writer provider
type writerProvider interface{ provide(s string) io.Writer }
type writerProviderImpl struct{}
func (p *writerProviderImpl) provide(s string) io.Writer {
switch strings.ToLower(s) {
case "stdout":
return &stdoutWriter{}
case "clipboard":
return &clipboardWriter{}
default:
return &fileWriter{path: s}
}
}
func closer(c io.Closer) {
if err := c.Close(); err != nil {
panic(err)
}
}