forked from JohannesKaufmann/html-to-markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrom.go
359 lines (314 loc) · 8.79 KB
/
from.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Package md converts html to markdown.
//
// converter := md.NewConverter("", true, nil)
//
// html = `<strong>Important</strong>`
//
// markdown, err := converter.ConvertString(html)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println("md ->", markdown)
// Or if you are already using goquery:
// markdown, err := converter.Convert(selec)
package md
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
)
type simpleRuleFunc func(content string, selec *goquery.Selection, options *Options) *string
type ruleFunc func(content string, selec *goquery.Selection, options *Options) (res AdvancedResult, skip bool)
// Converter is initialized by NewConverter.
type Converter struct {
m sync.RWMutex
rules map[string][]ruleFunc
keep map[string]struct{}
remove map[string]struct{}
Before func(selec *goquery.Selection)
// TODO: REMOVE!!!
// dom *goquery.Selection
// leading []string
// trailing []string
// Plugin -> ReportError, ... (not public)
domain string
options Options
}
// TODO: some STATE -> naming???
// TODO: should Plugin be called on every convert
func validate(val string, possible ...string) error {
for _, e := range possible {
if e == val {
return nil
}
}
return fmt.Errorf("field must be one of %v but got %s", possible, val)
}
func validateOptions(opt Options) error {
if err := validate(opt.HeadingStyle, "setext", "atx"); err != nil {
return err
}
if strings.Count(opt.HorizontalRule, "*") < 3 &&
strings.Count(opt.HorizontalRule, "_") < 3 &&
strings.Count(opt.HorizontalRule, "-") < 3 {
return errors.New("HorizontalRule must be at least 3 characters of '*', '_' or '-' but got " + opt.HorizontalRule)
}
if err := validate(opt.BulletListMarker, "-", "+", "*"); err != nil {
return err
}
if err := validate(opt.CodeBlockStyle, "indented", "fenced"); err != nil {
return err
}
if err := validate(opt.Fence, "```", "~~~"); err != nil {
return err
}
if err := validate(opt.EmDelimiter, "_", "*"); err != nil {
return err
}
if err := validate(opt.StrongDelimiter, "**", "__"); err != nil {
return err
}
if err := validate(opt.LinkStyle, "inlined", "referenced"); err != nil {
return err
}
if err := validate(opt.LinkReferenceStyle, "full", "collapsed", "shortcut"); err != nil {
return err
}
return nil
}
// NewConverter initializes a new converter and holds all the rules.
// - `domain` is used for links and images to convert relative urls ("/image.png") to absolute urls.
// - CommonMark is the default set of rules. Set enableCommonmark to false if you want
// to customize everything using AddRules and DONT want to fallback to default rules.
func NewConverter(domain string, enableCommonmark bool, options *Options) *Converter {
c := &Converter{
domain: domain,
rules: make(map[string][]ruleFunc),
keep: make(map[string]struct{}),
remove: make(map[string]struct{}),
}
if enableCommonmark {
c.AddRules(commonmark...)
c.remove["script"] = struct{}{}
c.remove["style"] = struct{}{}
c.remove["textarea"] = struct{}{}
}
// TODO: put domain in options?
if options == nil {
options = &Options{}
}
if options.HeadingStyle == "" {
options.HeadingStyle = "atx"
}
if options.HorizontalRule == "" {
options.HorizontalRule = "* * *"
}
if options.BulletListMarker == "" {
options.BulletListMarker = "-"
}
if options.CodeBlockStyle == "" {
options.CodeBlockStyle = "indented"
}
if options.Fence == "" {
options.Fence = "```"
}
if options.EmDelimiter == "" {
options.EmDelimiter = "_"
}
if options.StrongDelimiter == "" {
options.StrongDelimiter = "**"
}
if options.LinkStyle == "" {
options.LinkStyle = "inlined"
}
if options.LinkReferenceStyle == "" {
options.LinkReferenceStyle = "full"
}
c.options = *options
err := validateOptions(c.options)
if err != nil {
fmt.Println("markdown options is not valid:", err)
}
return c
}
func (c *Converter) getRuleFuncs(tag string) []ruleFunc {
c.m.RLock()
defer c.m.RUnlock()
r, ok := c.rules[tag]
if !ok || len(r) == 0 {
if _, keep := c.keep[tag]; keep {
return []ruleFunc{wrap(ruleKeep)}
}
if _, remove := c.remove[tag]; remove {
return nil // TODO:
}
return []ruleFunc{wrap(ruleDefault)}
}
return r
}
func wrap(simple simpleRuleFunc) ruleFunc {
return func(content string, selec *goquery.Selection, opt *Options) (AdvancedResult, bool) {
res := simple(content, selec, opt)
if res == nil {
return AdvancedResult{}, true
}
return AdvancedResult{Markdown: *res}, false
}
}
// AddRules adds the rules that are passed in to the converter.
func (c *Converter) AddRules(rules ...Rule) *Converter {
c.m.Lock()
defer c.m.Unlock()
for _, rule := range rules {
if len(rule.Filter) == 0 {
panic("you need to specify at least one filter for your rule")
}
for _, filter := range rule.Filter {
r, _ := c.rules[filter]
if rule.AdvancedReplacement != nil {
r = append(r, rule.AdvancedReplacement)
} else {
r = append(r, wrap(rule.Replacement))
}
c.rules[filter] = r
}
}
return c
}
// Keep certain html tags in the generated output.
func (c *Converter) Keep(tags ...string) *Converter {
c.m.Lock()
defer c.m.Unlock()
for _, tag := range tags {
c.keep[tag] = struct{}{}
}
return c
}
// Remove certain html tags from the source.
func (c *Converter) Remove(tags ...string) *Converter {
c.m.Lock()
defer c.m.Unlock()
for _, tag := range tags {
c.remove[tag] = struct{}{}
}
return c
}
// Plugin can be used to extends functionality beyond what
// is offered by commonmark.
type Plugin func(conv *Converter) []Rule
// Use can be used to add additional functionality to the converter. It is
// used when its not sufficient to use only rules for example in Plugins.
func (c *Converter) Use(plugins ...Plugin) *Converter {
for _, plugin := range plugins {
rules := plugin(c)
c.AddRules(rules...) // TODO: for better perfomance only use one lock for all plugins
}
return c
}
// TODO: Find
// TODO: ReportError
// TODO: AddLeading
// Timeout for the http client
var Timeout = time.Second * 10
var netClient = &http.Client{
Timeout: Timeout,
}
// DomainFromURL removes the path from the url.
func DomainFromURL(rawURL string) string {
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
u.Path = ""
return u.String()
}
var multipleNewLinesRegex = regexp.MustCompile(`[\n]{2,}`)
// Convert returns the content from a goquery selection.
// If you have a goquery document just pass in doc.Selection.
func (c *Converter) Convert(selec *goquery.Selection) string {
c.m.RLock()
domain := c.domain
options := c.options
l := len(c.rules)
if l == 0 {
panic("you have added no rules. either enable commonmark or add you own.")
}
c.m.RUnlock()
selec.Find("a[href]").Each(func(i int, s *goquery.Selection) {
s.SetAttr("data-index", strconv.Itoa(i+1))
})
res := c.selecToMD(domain, selec, &options)
markdown := res.Markdown
if res.Header != "" {
markdown = res.Header + "\n\n" + markdown
}
if res.Footer != "" {
markdown += "\n\n" + res.Footer
}
markdown = strings.TrimSpace(markdown)
markdown = multipleNewLinesRegex.ReplaceAllString(markdown, "\n\n")
return markdown
}
// ConvertReader returns the content from a reader and returns a buffer.
func (c *Converter) ConvertReader(reader io.Reader) (bytes.Buffer, error) {
var buffer bytes.Buffer
doc, err := goquery.NewDocumentFromReader(reader)
if err != nil {
return buffer, err
}
buffer.WriteString(
c.Convert(doc.Selection),
)
return buffer, nil
}
// ConvertResponse returns the content from a html response.
func (c *Converter) ConvertResponse(res *http.Response) (string, error) {
doc, err := goquery.NewDocumentFromResponse(res)
if err != nil {
return "", err
}
return c.Convert(doc.Selection), nil
}
// ConvertString returns the content from a html string. If you
// already have a goquery selection use `Convert`.
func (c *Converter) ConvertString(html string) (string, error) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return "", err
}
return c.Convert(doc.Selection), nil
}
// ConvertBytes returns the content from a html byte array.
func (c *Converter) ConvertBytes(bytes []byte) ([]byte, error) {
res, err := c.ConvertString(string(bytes))
if err != nil {
return nil, err
}
return []byte(res), nil
}
// ConvertURL returns the content from the page with that url.
func (c *Converter) ConvertURL(url string) (string, error) {
// not using goquery.NewDocument directly because of the timeout
resp, err := netClient.Get(url)
if err != nil {
return "", nil
}
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
return "", nil
}
domain := DomainFromURL(url)
if c.domain != domain {
return "", errors.New("expected " + c.domain + " as the domain but got " + domain)
}
return c.Convert(doc.Selection), nil
}