forked from buildkite/terminal-to-html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelement.go
222 lines (195 loc) · 5.04 KB
/
element.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
package terminal
import (
"encoding/base64"
"errors"
"fmt"
"mime"
"strings"
)
const (
ELEMENT_ITERM_IMAGE = iota
ELEMENT_IMAGE
ELEMENT_LINK
)
type element struct {
url string
alt string
contentType string
content string
height string
width string
elementType int
}
var errUnsupportedElementSequence = errors.New("Unsupported element sequence")
func (i *element) asHTML() string {
if i.elementType == ELEMENT_LINK {
content := i.content
if content == "" {
content = i.url
}
return fmt.Sprintf(`<a href="%s">%s</a>`, i.url, content)
}
alt := i.alt
if alt == "" {
alt = i.url
}
parts := []string{fmt.Sprintf(`alt="%s"`, alt)}
if i.elementType == ELEMENT_ITERM_IMAGE {
parts = append(parts, fmt.Sprintf(`src="data:%s;base64,%s"`, i.contentType, i.content))
} else {
parts = append(parts, fmt.Sprintf(`src="%s"`, i.url))
}
if i.width != "" {
parts = append(parts, fmt.Sprintf(`width="%s"`, i.width))
}
if i.height != "" {
parts = append(parts, fmt.Sprintf(`height="%s"`, i.height))
}
return fmt.Sprintf(`<img %s>`, strings.Join(parts, " "))
}
func parseElementSequence(sequence string) (*element, error) {
// Expect 1337;File=name=1.gif;inline=1:BASE64
args, elementType, content, err := splitAndVerifyElementSequence(sequence)
if err != nil {
if err == errUnsupportedElementSequence {
err = nil
}
return nil, err
}
tokens, err := tokenizeString(args, ';', '\\')
if err != nil {
return nil, err
}
imageInline := false
elem := &element{content: content, elementType: elementType}
for _, token := range tokens {
parts := strings.SplitN(token, "=", 2)
if len(parts) != 2 {
continue
}
key := parts[0]
val := parts[1]
switch strings.ToLower(key) {
case "name":
nameBytes, err := base64.StdEncoding.DecodeString(val)
if err != nil {
return nil, fmt.Errorf("name= value of %q is not valid base64", val)
}
elem.url = strings.Map(htmlStripper, string(nameBytes))
elem.contentType = contentTypeForFile(elem.url)
case "url":
elem.url = val
case "content":
elem.content = val
case "inline":
imageInline = val == "1"
case "width":
elem.width = parseImageDimension(val)
case "height":
elem.height = parseImageDimension(val)
case "alt":
elem.alt = val
}
}
if elem.elementType == ELEMENT_ITERM_IMAGE {
if elem.url == "" {
return nil, fmt.Errorf("name= argument not supplied, required to determine content type")
}
if elem.contentType == "" {
return nil, fmt.Errorf("can't determine content type for %q", elem.url)
}
} else {
if elem.url == "" {
return nil, fmt.Errorf("url= argument not supplied")
}
}
if elem.elementType == ELEMENT_ITERM_IMAGE && !imageInline {
// in iTerm2, if you don't specify inline=1, the image is merely downloaded
// and not displayed.
elem = nil
}
return elem, nil
}
func contentTypeForFile(filename string) string {
dot := strings.LastIndex(filename, ".")
if dot == -1 {
return ""
}
return mime.TypeByExtension(filename[dot:])
}
func parseImageDimension(s string) string {
s = strings.ToLower(s)
if !strings.HasSuffix(s, "px") && !strings.HasSuffix(s, "%") {
return s + "em"
} else {
return s
}
}
func htmlStripper(r rune) rune {
switch r {
case '<', '>', '\'', '"':
return -1
default:
return r
}
}
func splitAndVerifyElementSequence(s string) (arguments string, elementType int, content string, err error) {
if strings.HasPrefix(s, "1338;") {
return s[len("1338;"):], ELEMENT_IMAGE, "", nil
}
if strings.HasPrefix(s, "1339;") {
return s[len("1339;"):], ELEMENT_LINK, "", nil
}
prefixLen := len("1337;File=")
if !strings.HasPrefix(s, "1337;File=") {
return "", 0, "", errUnsupportedElementSequence
}
s = s[prefixLen:]
parts := strings.Split(s, ":")
if len(parts) != 2 {
return "", 0, "", fmt.Errorf("expected sequence to have one arguments part and one content part, got %d part(s)", len(parts))
}
elementType = ELEMENT_ITERM_IMAGE
arguments = parts[0]
content = parts[1]
if len(content) == 0 {
return "", 0, "", fmt.Errorf("image content missing")
}
_, err = base64.StdEncoding.DecodeString(content)
if err != nil {
return "", 0, "", fmt.Errorf("expected content part to be valid Base64")
}
return
}
func tokenizeString(input string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
inSingleQuotes := false
inDoubleQuotes := false
for _, rune := range input {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, rune)
case rune == '\'':
inSingleQuotes = !inSingleQuotes
case rune == '"':
inDoubleQuotes = !inDoubleQuotes
case rune == escape:
inEscape = true
case rune == sep && !inSingleQuotes && !inDoubleQuotes:
tokens = append(tokens, strings.Map(htmlStripper, string(runes)))
runes = runes[:0]
}
}
tokens = append(tokens, strings.Map(htmlStripper, string(runes)))
if inEscape {
err = errors.New("invalid terminal escape")
}
if inSingleQuotes || inDoubleQuotes {
err = errors.New("invalid syntax: unclosed quotation marks")
}
return tokens, err
}