-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.go
85 lines (68 loc) · 1.2 KB
/
output.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
package main
import (
"fmt"
"os"
"github.com/jskcnsl/eesc/config"
"github.com/spf13/cobra"
)
type output interface {
Write(string)
Writeln(string)
Close()
}
var (
_ output = &StdOutput{}
o output = nil
)
func initOutput(*cobra.Command, []string) error {
var err error
if config.OutputFile != "" {
fmt.Printf("store output to file: %s\n", config.OutputFile)
o, err = NewFileOutput(config.OutputFile)
if err != nil {
return err
}
} else {
o = NewStdOutput()
}
return nil
}
func closeOutput(*cobra.Command, []string) {
if o != nil {
o.Close()
}
}
func NewStdOutput() output {
return &StdOutput{}
}
type StdOutput struct {
}
func (o *StdOutput) Write(l string) {
fmt.Print(l)
}
func (o *StdOutput) Writeln(l string) {
fmt.Println(l)
}
func (o *StdOutput) Close() {
}
type FileOutput struct {
f *os.File
}
func NewFileOutput(fn string) (output, error) {
f, err := os.OpenFile(fn, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
return &FileOutput{
f: f,
}, err
}
func (o *FileOutput) Write(l string) {
_, _ = o.f.WriteString(l)
}
func (o *FileOutput) Writeln(l string) {
_, _ = o.f.WriteString(l + "\n")
}
func (o *FileOutput) Close() {
o.f.Close()
}