-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
transformCmd.go
117 lines (104 loc) · 2.48 KB
/
transformCmd.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
package cmd
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/jf-tech/go-corelib/ios"
"github.com/jf-tech/go-corelib/jsons"
"github.com/jf-tech/go-corelib/strs"
"github.com/spf13/cobra"
"github.com/jf-tech/omniparser"
"github.com/jf-tech/omniparser/transformctx"
)
var (
transformCmd = &cobra.Command{
Use: "transform",
Short: "Transforms input to desired output based on a schema.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if err := doTransform(); err != nil {
fmt.Println() // to sure cobra cli always write out "Error: ..." on a new line.
return err
}
return nil
},
}
schema string
input string
)
func init() {
transformCmd.Flags().StringVarP(&schema, "schema", "s", "", "schema file (required)")
_ = transformCmd.MarkFlagRequired("schema")
transformCmd.Flags().StringVarP(
&input, "input", "i", "", "input file (optional; if not specified, stdin/pipe is used)")
}
func openFile(label string, filepath string) (io.ReadCloser, error) {
if !ios.FileExists(schema) {
return nil, fmt.Errorf("%s file '%s' does not exist", label, filepath)
}
return os.Open(filepath)
}
func doTransform() error {
schemaName := filepath.Base(schema)
schemaReadCloser, err := openFile("schema", schema)
if err != nil {
return err
}
defer schemaReadCloser.Close()
inputReadCloser := io.ReadCloser(nil)
inputName := ""
if strs.IsStrNonBlank(input) {
inputName = filepath.Base(input)
inputReadCloser, err = openFile("input", input)
if err != nil {
return err
}
defer inputReadCloser.Close()
} else {
inputName = "(stdin)"
inputReadCloser = os.Stdin
// Note we don't defer Close() on this since os/golang runtime owns it.
}
schema, err := omniparser.NewSchema(schemaName, schemaReadCloser)
if err != nil {
return err
}
transform, err := schema.NewTransform(inputName, inputReadCloser, &transformctx.Ctx{})
if err != nil {
return err
}
doOne := func() (string, error) {
b, err := transform.Read()
if err != nil {
return "", err
}
return strings.Join(
strs.NoErrMapSlice(
strings.Split(jsons.BPJ(string(b)), "\n"),
func(s string) string { return "\t" + s }),
"\n"), nil
}
record, err := doOne()
if err == io.EOF {
fmt.Println("[]")
return nil
}
if err != nil {
return err
}
fmt.Printf("[\n%s", record)
for {
record, err = doOne()
if err == io.EOF {
break
}
if err != nil {
return err
}
fmt.Printf(",\n%s", record)
}
fmt.Println("\n]")
return nil
}