-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli.go
193 lines (168 loc) · 4.73 KB
/
cli.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package main
import (
"fmt"
"io"
"regexp"
"runtime"
"github.com/ujiro99/logcatf/logcat"
"github.com/Maki-Daisuke/go-lines"
log "github.com/Sirupsen/logrus"
"golang.org/x/text/encoding/japanese"
"golang.org/x/text/transform"
"gopkg.in/alecthomas/kingpin.v2"
)
// Exit codes are int values that represent an exit code for a particular error.
const (
ExitCodeOK int = 0
ExitCodeError int = 1 + iota
)
// CLI is the command line object
type CLI struct {
inStream io.Reader
outStream, errStream io.Writer
executors []Executor
}
var (
formatter Formatter
parser logcat.Parser
writer io.Writer
fmtc Colorizer
version string
)
// Run invokes the CLI with the given arguments.
func (cli *CLI) Run(args []string) int {
// initialize
err := cli.initialize(args)
if err != nil {
fmt.Fprintln(cli.errStream, err.Error())
log.Debug(err.Error())
return ExitCodeError
}
// let's start
for line := range lines.Lines(cli.inStream) {
item := cli.parseLine(line)
cli.execute(line, item)
}
log.Debugf("run finished")
return ExitCodeOK
}
// exec parse and format
func (cli *CLI) parseLine(line string) logcat.Entry {
item, err := parser.Parse(line)
if err != nil {
log.Debug(err.Error())
return nil
}
output := formatter.Format(&item)
fmtc.Fprintln(writer, output, item)
return item
}
func (cli *CLI) initialize(args []string) error {
// setup kingpin & parse args
var (
app = kingpin.New(Name, Message["commandDescription"])
format = app.Arg("format", Message["helpFormat"]).Default(DefaultFormat).String()
triggers = app.Flag("on", Message["helpTrigger"]).Short('o').RegexpList()
commands = app.Flag("command", Message["helpCommand"]).Short('c').Strings()
encode = app.Flag("encode", Message["helpEncode"]).Default(UTF8).String()
toCsv = app.Flag("to-csv", Message["helpToCsv"]).Bool()
color = app.Flag("color", Message["helpToColor"]).Bool()
colorV = app.Flag("color-v", Message["helpToColorV"]).PlaceHolder("COLOR").String()
colorD = app.Flag("color-d", Message["helpToColorD"]).PlaceHolder("COLOR").String()
colorI = app.Flag("color-i", Message["helpToColorI"]).PlaceHolder("COLOR").String()
colorW = app.Flag("color-w", Message["helpToColorW"]).PlaceHolder("COLOR").String()
colorE = app.Flag("color-e", Message["helpToColorE"]).PlaceHolder("COLOR").String()
colorF = app.Flag("color-f", Message["helpToColorF"]).PlaceHolder("COLOR").String()
)
app.HelpFlag.Short('h')
app.Version(version)
kingpin.MustParse(app.Parse(args[1:]))
// initialize colorizer
config := ColorConfig{
"V": *colorV,
"D": *colorD,
"I": *colorI,
"W": *colorW,
"E": *colorE,
"F": *colorF,
}
fmtc = Colorizer{}
fmtc.Init(*color, config)
parser = logcat.NewParser()
cli.initFormatter(*toCsv, *format)
cli.initWriter(*toCsv, *encode)
err := cli.initExecutors(*triggers, *commands)
if err != nil {
return err
}
log.WithFields(log.Fields{
"format": *format,
"trigger": *triggers,
"command": *commands}).Debug("Parameter initialized.")
return formatter.Verify()
}
// initialize Formatter
func (cli *CLI) initFormatter(toCsv bool, format string) {
if toCsv {
if format == DefaultFormat {
format = AllFormat
}
formatter = NewCsvFormatter(format)
} else {
format := fmtc.ReplaceColorCode(format)
formatter = &defaultFormatter{format: &format}
}
// convert format (long => short)
formatter.Normarize()
}
// initialize Writer
func (cli *CLI) initWriter(toCsv bool, encode string) {
if toCsv && runtime.GOOS == Windows && encode == "" {
encode = ShiftJIS
}
switch encode {
case ShiftJIS:
writer = transform.NewWriter(cli.outStream, japanese.ShiftJIS.NewEncoder())
case EUCJP:
writer = transform.NewWriter(cli.outStream, japanese.EUCJP.NewEncoder())
case ISO2022JP:
writer = transform.NewWriter(cli.outStream, japanese.ISO2022JP.NewEncoder())
default:
writer = cli.outStream
}
}
// initialize Executors
func (cli *CLI) initExecutors(triggers []*regexp.Regexp, commands []string) error {
if triggers == nil {
// if trigger not exists, not execute anything.
cli.executors = []Executor{&emptyExecutor{}}
} else {
if len(triggers) != len(commands) {
return &ParameterError{Message["msgCommandNumMismatch"]}
}
es := []Executor{}
for i, t := range triggers {
es = append(es, &executor{
trigger: t,
command: &(commands)[i],
Stdout: cli.errStream,
})
}
cli.executors = es
}
return nil
}
// execute calls multiple executors.
func (cli *CLI) execute(line string, item logcat.Entry) {
for _, e := range cli.executors {
e.IfMatch(line).Exec(item)
}
}
// ParameterError has error message of parameter.
type ParameterError struct {
msg string
}
// Error returns all error message.
func (e *ParameterError) Error() string {
return e.msg
}