-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
xq.go
115 lines (107 loc) · 2.5 KB
/
xq.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
package main
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/antchfx/xmlquery"
)
// set during built time
var (
name = "xq"
source = "unknown"
version = "unknown"
commit = "unknown"
platform = "unknown"
buildTime = "unknown"
)
var (
ErrInvalidFile = errors.New("invalid file")
ErrNoInput = errors.New("no input")
ErrMissingXpath = errors.New("missing xpath expression argument")
ErrXMLParse = errors.New("xmlparse error")
ErrXMLQuery = errors.New("xmlquery error")
)
func getReader(file string) (io.Reader, error) {
if file == "-" {
return os.Stdin, nil
}
if u, err := url.ParseRequestURI(file); err == nil && (u.Scheme == "http" || u.Scheme == "https") {
//nolint:gosec,bodyclose,noctx
resp, err := http.Get(file)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidFile, err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %s", ErrInvalidFile, resp.Status)
}
return resp.Body, nil
} else if err == nil && u.Scheme == "file" {
file = filepath.FromSlash(fmt.Sprintf("%s%s", u.Host, u.Path))
}
if file != "" {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidFile, err)
}
return f, nil
}
return nil, ErrNoInput
}
func parseArguments(_file string, _f string, _xpath string, _x string) (file string, xpath string, err error) {
if _f != "" {
file = _f
}
if _file != "" {
file = _file
}
if file == "-" || file == "" {
file = "-"
}
if _x != "" {
xpath = _x
}
if _xpath != "" {
xpath = _xpath
}
if xpath == "" {
err = ErrMissingXpath
return
}
return
}
func query(reader io.Reader, xpath string) error {
if readCloser, ok := reader.(io.ReadCloser); ok {
defer readCloser.Close()
}
doc, err := xmlquery.Parse(reader)
if err != nil {
return fmt.Errorf("%w: %s", ErrXMLParse, err)
}
list, err := xmlquery.QueryAll(doc, xpath)
if err != nil {
return fmt.Errorf("%w: %s", ErrXMLQuery, err)
}
for _, elem := range list {
if elem.Type == xmlquery.AttributeNode {
// do not nest attribute node in a tag
fmt.Fprintf(os.Stdout, "%s\n", elem.InnerText())
} else {
// prevent output of pseudo tags if root element was selected
isRoot := elem.Parent != nil
fmt.Fprintf(os.Stdout, "%s\n", elem.OutputXML(isRoot))
}
}
return nil
}
func xq(file string, xpath string) error {
if reader, err := getReader(file); err != nil {
return err
} else if err = query(reader, xpath); err != nil {
return err
}
return nil
}