-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcssformat.go
341 lines (310 loc) · 6.84 KB
/
cssformat.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
package csstool
import (
"bufio"
"bytes"
"io"
"log"
"github.com/tdewolff/parse/css"
)
type stack []io.Writer
func (s stack) Push(v io.Writer) stack {
return append(s, v)
}
func (s stack) Pop() (stack, io.Writer) {
l := len(s)
return s[:l-1], s[l-1]
}
func inArray(ary []string, val string) bool {
for _, a := range ary {
if val == a {
return true
}
}
return false
}
// CSSFormat contains formatting perferances for CSS
type CSSFormat struct {
Indent int
IndentTab bool
AlwaysSemicolon bool
RemoveAtRule []string // ignore things like "@media XXX"
RemoveSourceMap bool // remove comment with source map
Debug bool
Matcher matcher
}
// NewCSSFormat creates an initialized CSSFormat object
func NewCSSFormat(indent int, useTabs bool, m matcher) *CSSFormat {
if useTabs {
indent = 1
}
if m == nil {
m = &EmptyMatcher{}
}
return &CSSFormat{
Indent: indent,
IndentTab: useTabs,
Matcher: m,
}
}
// Format reformats CSS using a reader to output writer
func (c *CSSFormat) Format(r io.Reader, wraw io.Writer) error {
var err error
var w io.Writer
writers := make(stack, 0)
wbuf := bufio.NewWriter(wraw)
// w is the main writer that is used.
// adjusted to whatever the correct destination is
w = wbuf
// various states
qualified := 0
ruleCount := 0
indent := 0
skipRuleset := false
rulesetCount := 0
p := css.NewParser(r, false)
for {
gt, _, data := p.Next()
switch gt {
case css.ErrorGrammar:
wbuf.Flush()
if err == io.EOF {
err = nil
}
return err
// a comma-separated list of tags
// but not the last one .. so h1,h2,h3
// h1,h2 are here, but h3 is a beginRuleSetGrammar
case css.QualifiedRuleGrammar:
tokens := p.Values()
if c.Matcher.Remove(selectors(tokens)) {
if c.Debug {
log.Printf("cutting qualified rule %q", completeSelector(tokens))
}
continue
}
if qualified == 0 {
c.addIndent(w, indent)
} else {
c.writeComma(w)
}
qualified++
for _, t := range tokens {
w.Write(t.Data)
}
case css.BeginRulesetGrammar:
ruleCount = 0
tokens := p.Values()
if qualified == 0 {
if c.Matcher.Remove(selectors(tokens)) {
if c.Debug {
log.Printf("cutting ruleset1 %q", completeSelector(tokens))
}
indent++
skipRuleset = true
continue
}
c.addIndent(w, indent)
c.writeTokens(w, tokens)
c.writeLeftBrace(w)
indent++
continue
}
qualified = 0
indent++
if c.Matcher.Remove(selectors(tokens)) {
if c.Debug {
log.Printf("cutting qualified rule %q", completeSelector(tokens))
}
c.writeLeftBrace(w)
continue
}
c.writeComma(w)
c.writeTokens(w, tokens)
c.writeLeftBrace(w)
case css.EndRulesetGrammar:
indent--
if skipRuleset {
skipRuleset = false
continue
}
rulesetCount++
// add semicolon, even if the last rule
// i.e. color: #000;}
if c.AlwaysSemicolon {
w.Write([]byte{';'})
}
c.writeRightBrace(w, indent)
case css.BeginAtRuleGrammar:
// first compute the entire AtRule
atRule := []byte{}
atRule = append(atRule, data...)
tokens := p.Values()
// for '@media page', '@media' and 'page' has a required
// whitespace token and so must alway be printed. No
// need to write extra whitespace
//
// for '@media (page-width:...)' the whitespace between them
// is optional. Print it if desired.
if len(tokens) > 0 && tokens[0].TokenType != css.WhitespaceToken && c.Indent != 0 {
atRule = append(atRule, ' ')
}
for _, tok := range tokens {
atRule = append(atRule, tok.Data...)
}
// skip the "@media print" query
if inArray(c.RemoveAtRule, string(atRule)) {
// just skip over everything
nestdepth := 1
for nestdepth != 0 {
gt, _, _ = p.Next()
if gt == css.ErrorGrammar {
wbuf.Flush()
return nil
}
if gt == css.EndAtRuleGrammar {
nestdepth--
}
if gt == css.BeginAtRuleGrammar {
nestdepth++
}
}
continue
}
ruleCount = 0
rulesetCount = 0
// first render the @rule
// into it's own buffer
// save existing context
writers = writers.Push(w)
w = &bytes.Buffer{}
c.addIndent(w, indent)
w.Write(atRule)
c.writeLeftBrace(w)
// set up new buffer for content
writers = writers.Push(w)
w = &bytes.Buffer{}
indent++
case css.EndAtRuleGrammar:
// have we written anything?
contents := w.(*bytes.Buffer).Bytes()
writers, w = writers.Pop()
header := w.(*bytes.Buffer).Bytes()
writers, w = writers.Pop()
indent--
if len(contents) == 0 {
// no
continue
}
w.Write(header)
w.Write(contents)
c.writeRightBrace(w, indent)
case css.CommentGrammar:
if c.RemoveSourceMap && bytes.Contains(data, []byte("sourceMappingURL")) {
continue
}
w.Write(data)
c.addNewline(w)
case css.CustomPropertyGrammar:
if skipRuleset {
continue
}
c.addIndent(w, indent)
w.Write(data)
// do not add space
w.Write([]byte{':'})
c.writeTokens(w, p.Values())
c.writeSemicolon(w)
case css.DeclarationGrammar:
if skipRuleset {
continue
}
if ruleCount != 0 {
c.writeSemicolon(w)
}
ruleCount++
c.addIndent(w, indent)
w.Write(data)
w.Write([]byte{':'})
c.addSpace(w)
tokens := p.Values()
for _, tok := range tokens {
// add space before !important
if len(tok.Data) == 1 && tok.Data[0] == '!' {
c.addSpace(w)
}
w.Write(tok.Data)
}
case css.TokenGrammar:
w.Write(data)
case css.AtRuleGrammar:
c.addIndent(w, indent)
w.Write(data)
c.writeTokens(w, p.Values())
c.writeSemicolon(w)
default:
panic("Unknown grammar: " + gt.String() + " " + string(data))
}
}
}
var (
spaces = []byte(" ")
tabs = []byte("\t\t\t\t")
)
func (c *CSSFormat) addIndent(w io.Writer, depth int) {
if c.Indent == 0 || depth == 0 {
return
}
if c.IndentTab {
w.Write(tabs[:depth])
return
}
w.Write(spaces[:c.Indent*depth])
}
func (c *CSSFormat) addSpace(w io.Writer) {
if c.Indent == 0 {
return
}
w.Write([]byte{' '})
}
func (c *CSSFormat) addNewline(w io.Writer) {
if c.Indent == 0 {
return
}
w.Write([]byte{'\n'})
}
func (c *CSSFormat) writeComma(w io.Writer) {
if c.Indent == 0 {
w.Write([]byte{','})
return
}
w.Write([]byte{',', ' '})
}
func (c *CSSFormat) writeLeftBrace(w io.Writer) {
if c.Indent == 0 {
w.Write([]byte{'{'})
return
}
w.Write([]byte{' ', '{', '\n'})
}
func (c *CSSFormat) writeRightBrace(w io.Writer, depth int) {
if c.Indent == 0 {
w.Write([]byte{'}'})
return
}
c.addNewline(w)
c.addIndent(w, depth)
w.Write([]byte{'}'})
c.addNewline(w)
}
func (c *CSSFormat) writeSemicolon(w io.Writer) {
if c.Indent == 0 {
w.Write([]byte{';'})
return
}
w.Write([]byte{';', '\n'})
}
func (c *CSSFormat) writeTokens(w io.Writer, tokens []css.Token) {
for _, tok := range tokens {
w.Write(tok.Data)
}
}