-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
133 lines (109 loc) · 2.59 KB
/
main.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
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/tommy351/rdb-go"
)
// nolint: gochecknoglobals
var (
outputFormat string
rootCmd = &cobra.Command{
Use: "rdb [path]",
Args: cobra.MaximumNArgs(1),
Example: formatExamples([][]string{
{"Parse a RDB dump file.", "rdb path/to/dump.rdb"},
{"Read RDB from stdin.", "cat file | rdb"},
}),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
var printer Printer
writer := bufio.NewWriter(os.Stdout)
defer writer.Flush()
switch outputFormat {
case "json":
printer = NewJSONPrinter(writer)
default:
// nolint: goerr113
return fmt.Errorf("unsupported format %q", outputFormat)
}
var reader io.Reader
if len(args) > 0 {
file, err := os.Open(args[0])
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
reader = file
} else {
reader = bufio.NewReader(os.Stdin)
}
return printParserData(reader, printer)
},
}
)
func formatExamples(examples [][]string) string {
lines := make([]string, len(examples))
indent := " "
for i, v := range examples {
lines[i] = indent + "# " + v[0] + "\n" + indent + v[1]
}
return strings.Join(lines, "\n\n")
}
func main() {
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output", "o", "json", "output format")
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func printParserData(reader io.Reader, printer Printer) error {
parser := rdb.NewParser(reader)
if err := printer.Start(); err != nil {
return fmt.Errorf("printer start error: %w", err)
}
for {
data, err := parser.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("parser error: %w", err)
}
switch v := data.(type) {
case *rdb.StringData:
err = printer.String(v)
case *rdb.ListHead:
err = printer.ListHead(v)
case *rdb.ListEntry:
err = printer.ListEntry(v)
case *rdb.ListData:
err = printer.ListData(v)
case *rdb.SetHead:
err = printer.SetHead(v)
case *rdb.SetEntry:
err = printer.SetEntry(v)
case *rdb.SetData:
err = printer.SetData(v)
case *rdb.SortedSetHead:
err = printer.SortedSetHead(v)
case *rdb.SortedSetEntry:
err = printer.SortedSetEntry(v)
case *rdb.SortedSetData:
err = printer.SortedSetData(v)
case *rdb.HashHead:
err = printer.HashHead(v)
case *rdb.HashEntry:
err = printer.HashEntry(v)
case *rdb.HashData:
err = printer.HashData(v)
}
if err != nil {
return fmt.Errorf("printer error: %w", err)
}
}
return printer.End()
}