-
Notifications
You must be signed in to change notification settings - Fork 11
/
cascadia_main.go
218 lines (190 loc) · 5.61 KB
/
cascadia_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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
////////////////////////////////////////////////////////////////////////////
// Program: cascadia
// Purpose: go cascadia CSS selection from command line
// Authors: Tong Sun (c) 2016-2023, All rights reserved
////////////////////////////////////////////////////////////////////////////
//go:generate sh -v cascadia_cliGen.sh
package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/andybalholm/cascadia"
"github.com/mkideal/cli"
"golang.org/x/net/html"
)
////////////////////////////////////////////////////////////////////////////
// Constant and data type/structure definitions
const (
IsRaw = "RAW"
WrapHTMLEnd = `</body>`
)
// The OptsT type defines all the configurable options from cli.
type OptsT struct {
CSS []string
TextOut bool
TextRaw bool
Piece PieceStyleMap
Deli string
WrapHTML bool
Style string
Base string
Quiet bool
Verbose int
}
////////////////////////////////////////////////////////////////////////////
// Global variables definitions
var (
progname = "cascadia"
version = "1.3.0"
date = "2023-06-30"
rootArgv *rootT
// Opts store all the configurable options
Opts OptsT
)
var WrapHTMLBeg string
////////////////////////////////////////////////////////////////////////////
// Function definitions
func main() {
cli.SetUsageStyle(cli.DenseNormalStyle)
if err := cli.Root(root).Run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Println("")
}
//==========================================================================
// css selection
func CascadiaC(ctx *cli.Context) error {
// ctx.JSON(ctx.RootArgv())
// fmt.Println()
// ctx.JSON(ctx.Argv())
// fmt.Println()
argv := ctx.Argv().(*rootT)
WrapHTMLBeg = fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base href="%s">
%s
</head>
<body>`, argv.Base, argv.Style)
Opts.CSS, Opts.Piece, Opts.Deli,
Opts.WrapHTML, Opts.TextOut, Opts.TextRaw, Opts.Quiet =
argv.CSS, argv.Piece, argv.Deli,
argv.WrapHTML, argv.TextOut, argv.TextRaw, argv.Quiet
Cascadia(argv.Filei, argv.Fileo, Opts)
argv.Filei.Close()
argv.Fileo.Close()
return nil
}
//--------------------------------------------------------------------------
// Cascadia filters the input buffer/stream `bi` with CSS selectors array `Opts.CSS` and write to the output buffer/stream `bw`.
func Cascadia(bi io.Reader, bw io.Writer, Opts OptsT) error {
cssa, piece, deli, wrapHTML, textOut, textRaw, beQuiet :=
Opts.CSS, Opts.Piece, Opts.Deli,
Opts.WrapHTML, Opts.TextOut, Opts.TextRaw, Opts.Quiet
if wrapHTML {
fmt.Fprintln(bw, WrapHTMLBeg)
}
if len(piece.Values) == 0 {
// no sub CSS selectors -- none-block selection mode
if textOut {
doc, err := goquery.NewDocumentFromReader(bi)
abortOn("Input", err)
for _, css := range cssa {
// Process each item block
doc.Find(css).Each(func(index int, item *goquery.Selection) {
//fmt.Printf("] #%d: %s\n", index, item.Text())
if textRaw {
fmt.Fprintf(bw, "%s%s",
item.Text(), deli)
} else {
fmt.Fprintf(bw, "%s%s",
strings.TrimSpace(item.Text()), deli)
}
fmt.Fprintf(bw, "\n")
})
}
} else {
doc, err := html.Parse(bi)
abortOn("Input", err)
for _, css := range cssa {
c, err := cascadia.Compile(css)
abortOn("CSS Selector string "+css, err)
// https://godoc.org/github.com/andybalholm/cascadia
ns := c.MatchAll(doc)
if !beQuiet {
fmt.Fprintf(os.Stderr, "%d elements for '%s':\n", len(ns), css)
}
for _, n := range ns {
html.Render(bw, n)
fmt.Fprintf(bw, "\n")
}
}
}
} else {
// have sub CSS selectors within -css -- block selection mode
// fmt.Printf("%v\n", piece)
// https://godoc.org/github.com/PuerkitoBio/goquery
// for debug
//doc, err := goquery.NewDocumentFromReader(strings.NewReader(testhtml))
doc, err := goquery.NewDocumentFromReader(bi)
abortOn("Input", err)
// Print csv headers
for _, key := range piece.Keys {
fmt.Fprintf(bw, "%s%s", key, deli)
}
fmt.Fprintf(bw, "\n")
// Process each item block
doc.Find(cssa[0]).Each(func(index int, item *goquery.Selection) {
//fmt.Printf("] #%d: %s\n", index, item.Text())
for _, key := range piece.Keys {
//fmt.Printf("] %s: %s\n", key, piece.Values[key])
switch piece.PieceStyles[key] {
case PieceStyleRAW:
html.Render(bw, item.Find(piece.Values[key]).Get(0))
fmt.Fprintf(bw, deli)
case PieceStyleATTR:
fmt.Fprintf(bw, "%s%s",
item.AttrOr(piece.Values[key], ""), deli)
case PieceStyleTEXT:
fmt.Fprintf(bw, "%s%s",
item.Find(piece.Values[key]).Contents().Text(), deli)
}
}
fmt.Fprintf(bw, "\n")
})
}
if wrapHTML {
fmt.Fprintln(bw, WrapHTMLEnd)
}
return nil
}
//==========================================================================
// support functions
// abortOn will quit on anticipated errors gracefully without stack trace
func abortOn(errCase string, e error) {
if e != nil {
fmt.Printf("[%s] %s error: %v\n", progname, errCase, e)
os.Exit(1)
}
}
//==========================================================================
// for debug
// echo a | cascadia -i -o -c "[align=\"justify\"]" -p Bold="b"
const testhtml = `
<div class="container">
<div class="row">
<div class="col-lg-8">
<p align="justify"><b>Name</b>Priyaka</p>
<p align="justify"><b>Surname</b>Patil</p>
<p align="justify"><b>Adress</b><br>India,Kolhapur</p>
<p align="justify"><b>Hobbies </b><br>Playing</p>
<p align="justify"><b>Eduction</b><br>12th</p>
<p align="justify"><b>School</b><br>New Highschool</p>
</div>
</div>
</div>
`