[Golang] Minify CSS


Minify CSS via Golang.

The steps:

  1. Concatenate all CSS file.
  2. Remove C/C++ comments [2] [3]
  3. Remove all leading and trailing white space of each line.
mincss.go | repository | view raw
 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
package mincss

import (
	"bufio"
	"bytes"
	"io/ioutil"
	"regexp"
	"strings"
)

func RemoveCStyleComments(content []byte) []byte {
	// http://blog.ostermiller.org/find-comment
	ccmt := regexp.MustCompile(`/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/`)
	return ccmt.ReplaceAll(content, []byte(""))
}

func RemoveCppStyleComments(content []byte) []byte {
	cppcmt := regexp.MustCompile(`//.*`)
	return cppcmt.ReplaceAll(content, []byte(""))
}

func concatenateCSS(cssPathes []string) []byte {
	var cssAll []byte
	for _, cssPath := range cssPathes {
		println("concatenating " + cssPath + " ...")
		b, err := ioutil.ReadFile(cssPath)
		if err != nil {
			panic(err)
		}
		cssAll = append(cssAll, b...)
	}
	return cssAll
}

func MinifyCSS(cssPathes []string) string {
	cssAll := concatenateCSS(cssPathes)
	cssAllNoComments := RemoveCppStyleComments(RemoveCStyleComments(cssAll))

	// read line by line
	minifiedCss := ""
	scanner := bufio.NewScanner(bytes.NewReader(cssAllNoComments))
	for scanner.Scan() {
		// all leading and trailing white space of each line are removed
		minifiedCss += strings.TrimSpace(scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		panic(err)
	}

	return minifiedCss
}
mincss_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package mincss

import "testing"

func TestMinifyCSS(t *testing.T) {
	cssPathes := []string{
		"/home/siongui/dev/pali/tipitaka/app/css/tipitaka-latn.css",
		"/home/siongui/dev/pali/tipitaka/app/css/app.css",
	}
	minifiedCss := MinifyCSS(cssPathes)
	println(minifiedCss)
}

Tested on: Ubuntu Linux 15.10, Go 1.6.


References:

[1]regex match c comments
[2]Finding Comments in Source Code Using Regular Expressions – Stephen Ostermiller
[3]Comments - cppreference.com
[4]regexp - The Go Programming Language
[5]ioutil - The Go Programming Language
[6]bufio - The Go Programming Language
[7]bytes - The Go Programming Language
[8]strings - The Go Programming Language