-
Notifications
You must be signed in to change notification settings - Fork 3
/
transform.go
76 lines (73 loc) · 2.26 KB
/
transform.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
package l9filter
import (
"errors"
"github.com/LeakIX/l9filter/transformer"
"io"
"log"
"os"
)
type TransformCommand struct {
InputFormat string `required help:"input format" short:"i"`
OutputFormat string `required help:"output format" short:"o"`
SourceFile string `help:"Input file, stdin if none" short:"s"`
TargetFile string `help:"Output file, stdout if none" short:"f"`
PortFilter string `help:"Filter on port" short:"p"`
TypeFilter string `help:"Filter on type" short:"t"`
InputTransformer transformer.TransformerInterface `kong:"-"`
OutputTransformer transformer.TransformerInterface `kong:"-"`
LogWriter io.Writer `kong:"-"`
L9Sources []string `short:"l" default:"l9filter"`
}
func (cmd *TransformCommand) Run() error {
transformer.L9Sources = cmd.L9Sources
for _, trs := range transformer.Transformers {
if cmd.InputFormat == trs.Name() {
trs.SetReader(os.Stdin)
if len(cmd.SourceFile) > 0 {
inputFile, err := os.Open(cmd.SourceFile)
if err != nil {
return err
}
trs.SetReader(inputFile)
}
log.Println("selected input: " + trs.Name())
cmd.InputTransformer = trs
}
if cmd.OutputFormat == trs.Name() {
trs.SetWriter(os.Stdout)
if len(cmd.TargetFile) > 0 {
_, err := os.Stat(cmd.TargetFile)
if err == nil {
return os.ErrExist
}
outputFile, err := os.Create(cmd.TargetFile)
if err != nil {
return err
}
trs.SetWriter(outputFile)
}
log.Println("selected output: " + trs.Name())
cmd.OutputTransformer = trs
}
}
if cmd.InputTransformer == nil {
return errors.New("input format doesn't exists")
}
if cmd.OutputTransformer == nil {
return errors.New("output format doesn't exists")
}
for {
err := cmd.InputTransformer.Decode(cmd.OutputTransformer)
if err != nil {
if _, isNoDataError := err.(*transformer.NoDataError); isNoDataError {
// Happens when we meet comments ect ... we can safely skip
continue
}
if err.Error() == "EOF" {
// We done with input, close output and leave
os.Exit(0)
}
return err
}
}
}