/
convert.go
311 lines (255 loc) · 6.91 KB
/
convert.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
package ditaconvert
import (
"bytes"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"io"
"path"
"strings"
"github.com/raintreeinc/ditaconvert/html"
)
type TokenProcessor func(*Context, *xml.Decoder, xml.StartElement) error
type Renaming struct{ Name, AddClass string }
type Rules struct {
CustomResolveLink func(url string) (href, title, synopsis string, internal bool)
Rename map[string]Renaming
Skip map[string]bool
Unwrap map[string]bool
Custom map[string]TokenProcessor
}
type Context struct {
Index *Index
Topic *Topic
Rules *Rules
Encoder *html.Encoder
Output *bytes.Buffer
DecodingPath string
Errors []error
}
func NewConversion(index *Index, topic *Topic) *Context {
var out bytes.Buffer
return &Context{
Index: index,
Topic: topic,
Encoder: html.NewEncoder(&out),
Output: &out,
Rules: NewDefaultRules(),
DecodingPath: topic.Path,
}
}
func (context *Context) check(err error) bool {
if err != nil {
context.Errors = append(context.Errors, err)
return true
}
return false
}
func (context *Context) errorf(format string, args ...interface{}) {
err := fmt.Errorf(format, args...)
context.Errors = append(context.Errors, err)
}
func (context *Context) Run() error {
topic := context.Topic.Original
if topic == nil {
return fmt.Errorf("no associated topic")
}
body := ""
for _, node := range topic.Elements {
if IsBodyTag(node.XMLName.Local) {
if body != "" {
context.errorf("multiple body tags")
continue
}
body = node.Content
}
}
if body == "" && topic.ShortDesc.Content == "" {
context.errorf("page content missing")
}
defer context.Encoder.Flush()
if topic.ShortDesc.Content != "" {
context.Encoder.WriteStart("p",
xml.Attr{Name: xml.Name{Local: "class"}, Value: "synopsis"})
// add shortdesc
if err := context.Parse(topic.ShortDesc.Content); err != nil {
return err
}
context.Encoder.WriteEnd("p")
}
// add body
if err := context.Parse(body); err != nil {
return err
}
// add related links
return nil
}
// checks wheter dita tag corresponds to some "root element"
func IsBodyTag(tag string) bool { return strings.Contains(tag, "body") }
func (context *Context) Parse(data string) error {
dec := xml.NewDecoder(strings.NewReader(data))
return context.Recurse(dec)
}
var ErrSkip = errors.New("")
func (context *Context) RecurseChildCount(dec *xml.Decoder) (error, int) {
count := 0
for {
token, err := dec.Token()
if err != nil {
if err == io.EOF {
return nil, count
}
return err, count
}
if _, ended := token.(xml.EndElement); ended {
return nil, count
}
count++
if err := context.Handle(dec, token); err != nil {
return err, count
}
}
}
func (context *Context) Recurse(dec *xml.Decoder) error {
err, _ := context.RecurseChildCount(dec)
return err
}
func (context *Context) EmitWithChildren(dec *xml.Decoder, start xml.StartElement) error {
// encode starting tag and attributes
if err := context.Encoder.Encode(start); err != nil {
return err
}
// recurse on child tokens
err := context.Recurse(dec)
// always encode ending tag
context.check(context.Encoder.Encode(xml.EndElement{start.Name}))
return err
}
func (context *Context) Handle(dec *xml.Decoder, token xml.Token) error {
// should we just skip the token?
if context.ShouldSkip(token) {
dec.Skip()
return nil
}
// should we inline something from somewhere else?
if IsConref(token) {
return context.HandleConref(dec, token.(xml.StartElement))
}
startdepth := context.Encoder.Depth()
defer func() {
if startdepth != context.Encoder.Depth() {
fmt.Println(context.Encoder.Stack())
panic("mismatched start and end tag in html output")
}
}()
// should we unwrap the tag?
if context.ShouldUnwrap(token) {
return context.Recurse(dec)
}
// is it a starting token?
if start, isStart := token.(xml.StartElement); isStart {
// is it custom already before naming
if process, isCustom := context.Rules.Custom[start.Name.Local]; isCustom {
return process(context, dec, start)
}
// handle tag renaming
if renaming, ok := context.Rules.Rename[start.Name.Local]; ok {
// setAttr(&start, "data-dita", start.Name.Local)
start.Name.Local = renaming.Name
setAttr(&start, "class", renaming.AddClass)
}
// is it custom after renaming?
if process, isCustom := context.Rules.Custom[start.Name.Local]; isCustom {
return process(context, dec, start)
}
return context.EmitWithChildren(dec, start)
}
// otherwise, encode as is
return context.Encoder.Encode(token)
}
func (context *Context) InlinedImageURL(href string) string {
if strings.HasPrefix(href, "http:") || strings.HasPrefix(href, "https:") {
return href
}
directory := path.Dir(context.DecodingPath)
name := path.Join(directory, href)
data, _, err := context.Index.ReadFile(name)
if err != nil {
context.errorf("invalid image link %s: %s", href, err)
return href
}
encoded := base64.StdEncoding.EncodeToString(data)
ext := strings.ToLower(path.Ext(name))
if ext == "" {
context.errorf("invalid image link: %s", href)
return href
}
if ext == "jpg" {
ext = "jpeg"
}
return "data:image/" + ext + ";base64," + encoded
}
func (context *Context) ResolveLinkInfo(url string) (href, title, synopsis string, internal bool) {
if strings.HasPrefix(url, "http:") || strings.HasPrefix(url, "https:") || strings.HasPrefix(url, "mailto:") {
return url, "", "", false
}
var selector string
url, selector = SplitLink(url)
if url == "" {
return "#" + selector, "", "", true
}
name := context.DecodingPath
if url != "" {
name = path.Join(path.Dir(context.DecodingPath), url)
}
topic, ok := context.Index.Topics[CanonicalPath(name)]
if !ok {
context.errorf("did not find topic %v [%v%v]", name, url, selector)
return "", "", "", false
}
if selector != "" {
var err error
title, err = ExtractTitle(topic.Raw, selector)
if err != nil {
context.errorf("unable to extract title from %v [%v%v]: %v", name, url, selector, err)
}
}
if title == "" && topic.Original != nil {
title = topic.Title
if selector == "" {
synopsis, _ = topic.Original.ShortDesc.Text()
}
}
if selector != "" {
return trimext(url) + ".html#" + selector, title, synopsis, true
}
return trimext(url) + ".html", title, synopsis, true
}
func (context *Context) ShouldSkip(token xml.Token) bool {
start, isStart := token.(xml.StartElement)
if !isStart {
return false
}
if context.Rules.Skip[start.Name.Local] {
return true
}
if !isWebAudience(getAttr(&start, "audience"), getAttr(&start, "print"), getAttr(&start, "deliveryTarget")) {
return true
}
return false
}
func (context *Context) ShouldUnwrap(token xml.Token) bool {
start, isStart := token.(xml.StartElement)
if !isStart {
return false
}
return context.Rules.Unwrap[start.Name.Local]
}
func IsConref(token xml.Token) bool {
start, isStart := token.(xml.StartElement)
if !isStart {
return false
}
return getAttr(&start, "conref") != "" || getAttr(&start, "conkeyref") != ""
}