CSS Minify & Beautify — Go source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package cssminify is the Go twin of CosmoDev's src/lib/css-minify.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// css-minify_test.go share vectors with src/lib/css-minify.test.ts so the two
// implementations are held to the same contract.
//
// One scanner splits the input into strings (opaque \x00n\x00 sentinels),
// comments (dropped) and text; every textual rule then runs on the masked
// text with RE2-compatible regexes (no lookaround, no backreferences) so the
// Go CLI twin reproduces byte-identical output:
//
// minify — collapse whitespace, strip spaces around {} ; : , > (deliberately
// NOT + or ~, so sibling combinators keep their spaces), drop semicolons
// directly before }, lowercase hexes, shorten only compressible #aabbcc
// (never 8-digit with alpha), strip leading zeros (0.5 → .5) and trailing
// fraction zeros (1.50 → 1.5, 1.00 → 1, .00 → 0).
// beautify — one selector line per block, one declaration per line at
// 2-space depth, each declaration keeping its own semicolon.
package cssminify
import (
"regexp"
"strconv"
"strings"
)
// Result is the outcome of a formatting run, mirroring the TS CssFormatResult
// union. Error is "" (zero value) when there was no error, standing in for
// the TS `error: string | null` null case.
type Result struct {
Output string
Error string
}
// Error strings returned in Result.Error, byte-identical to the TS messages.
const (
errUnterminatedString = "Unterminated string"
errUnterminatedComment = "Unterminated comment"
errNoSelector = "Block without a selector"
errUnbalancedBrace = "Unbalanced }"
errUnclosedBlock = "Unclosed block"
)
var (
// ws collapses every whitespace run to a single space.
ws = regexp.MustCompile(`\s+`)
// structStrip removes whitespace around structural punctuation. It
// deliberately excludes + and ~ so sibling combinators keep their spaces.
structStrip = regexp.MustCompile(`\s*([{};:,>])\s*`)
// trailingSemis drops runs of semicolons directly before a closing brace.
trailingSemis = regexp.MustCompile(`;+}`)
// hexLower lowercases every '#' followed by 3-8 hex digits.
hexLower = regexp.MustCompile(`#[0-9a-fA-F]{3,8}`)
// hexPair matches a 6-digit lowercase hex followed by a non-hex char or
// end of input. The TS pattern uses backreferences
// (#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)), which RE2 does
// not support; shortenHexPair below re-implements the pair test on the
// matched text (a failing match consumes the same bytes as a failed TS
// match attempt, so the set of rewritten positions is identical).
hexPair = regexp.MustCompile(`#[0-9a-f]{6}([^0-9a-f]|$)`)
// leadingZero strips a 0 directly before a decimal fraction (0.5 → .5)
// when not preceded by an identifier-ish char (letters, digits, _ . # $ % -).
leadingZero = regexp.MustCompile(`(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)`)
// fractionZeros strips trailing zeros after a non-zero fraction (1.50 → 1.5).
fractionZeros = regexp.MustCompile(`(\.[0-9]*[1-9])0+([^0-9]|$)`)
// integralZeros drops an all-zero fraction after a whole number (1.00 → 1).
integralZeros = regexp.MustCompile(`(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)`)
// dotZeros turns a bare all-zero fraction into a 0 (.00 → 0). The TS
// replacement '$10$2' is group 1 + literal '0' + group 2, hence ${1}0
// here (a bare $10 would be read as group 10 and expand empty).
dotZeros = regexp.MustCompile(`(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)`)
// sentinel finds the \x00n\x00 masks emitted by mask().
sentinel = regexp.MustCompile("\x00([0-9]+)\x00")
)
// mask scans raw CSS into a masked text where every string literal is
// replaced by a \x00n\x00 sentinel (n = index into strings) and every
// /* ... */ comment is dropped. Strings are byte-preserved: a backslash
// escapes the next character, so \' or \" never closes the literal. It
// mirrors mask() in css-minify.ts; the returned error is empty on success.
func mask(raw string) (masked string, strs []string, err string) {
var b strings.Builder
for i := 0; i < len(raw); {
ch := raw[i]
if ch == '"' || ch == '\'' {
start := i
i++
for i < len(raw) && raw[i] != ch {
if raw[i] == '\\' && i+1 < len(raw) {
i++ // escaped char: skip it verbatim
}
i++
}
if i >= len(raw) {
return "", nil, errUnterminatedString
}
i++ // closing quote
strs = append(strs, raw[start:i])
b.WriteString("\x00")
b.WriteString(strconv.Itoa(len(strs) - 1))
b.WriteString("\x00")
} else if ch == '/' && i+1 < len(raw) && raw[i+1] == '*' {
end := strings.Index(raw[i+2:], "*/")
if end < 0 {
return "", nil, errUnterminatedComment
}
i += 2 + end + 2
} else {
b.WriteByte(ch)
i++
}
}
return b.String(), strs, ""
}
// unmask substitutes the sentinels back with the original string literals,
// byte-for-byte.
func unmask(text string, strs []string) string {
return sentinel.ReplaceAllStringFunc(text, func(m string) string {
n, convErr := strconv.Atoi(m[1 : len(m)-1])
if convErr != nil || n < 0 || n >= len(strs) {
return m // unreachable for well-formed mask() output
}
return strs[n]
})
}
// shortenHexPair re-implements the TS backreference replacement
// '#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)' → '#$1$2$3$4':
// shorten #aabbcc to #abc only when both digits of each pair match, and only
// when the hex is not followed by further hex digits (so 8-digit #rrggbbaa
// with alpha is never touched). m is '#abcdef' plus the one non-hex context
// char (or nothing when the hex ends the input).
func shortenHexPair(m string) string {
if m[1] == m[2] && m[3] == m[4] && m[5] == m[6] {
return "#" + m[1:2] + m[3:4] + m[5:6] + m[7:]
}
return m
}
// MinifyCss conservatively minifies CSS — see the package header for the
// exact rule list. It is the Go twin of minifyCss() in css-minify.ts and must
// agree with it on every shared vector.
func MinifyCss(raw string) Result {
text := strings.TrimSpace(raw)
if text == "" {
return Result{} // empty/whitespace-only input is NOT an error
}
masked, strs, maskErr := mask(text)
if maskErr != "" {
return Result{Error: maskErr}
}
css := ws.ReplaceAllString(masked, " ")
css = structStrip.ReplaceAllString(css, "$1")
css = trailingSemis.ReplaceAllString(css, "}")
css = strings.TrimSpace(css)
css = hexLower.ReplaceAllStringFunc(css, strings.ToLower)
css = hexPair.ReplaceAllStringFunc(css, shortenHexPair)
css = leadingZero.ReplaceAllString(css, "$1$2")
css = fractionZeros.ReplaceAllString(css, "$1$2")
css = integralZeros.ReplaceAllString(css, "$1$2$3")
css = dotZeros.ReplaceAllString(css, "${1}0$2")
return Result{Output: unmask(css, strs)}
}
// BeautifyCss lays out CSS structurally: one selector line per block, one
// declaration per line at 2-space depth, each declaration keeping its own
// semicolon; empty declarations are skipped. It is the Go twin of
// beautifyCss() in css-minify.ts.
func BeautifyCss(raw string) Result {
text := strings.TrimSpace(raw)
if text == "" {
return Result{} // empty/whitespace-only input is NOT an error
}
masked, strs, maskErr := mask(text)
if maskErr != "" {
return Result{Error: maskErr}
}
css := ws.ReplaceAllString(masked, " ")
var out strings.Builder
var buf strings.Builder
depth := 0
flushDecl := func(semi bool) {
decl := strings.TrimSpace(ws.ReplaceAllString(buf.String(), " "))
if decl != "" { // empty declarations (;;, dangling ;) are skipped
out.WriteString(strings.Repeat(" ", depth))
out.WriteString(decl)
if semi {
out.WriteString(";")
}
out.WriteString("\n")
}
buf.Reset()
}
for i := 0; i < len(css); i++ {
switch css[i] {
case '{':
sel := strings.TrimSpace(ws.ReplaceAllString(buf.String(), " "))
buf.Reset()
if sel == "" {
return Result{Error: errNoSelector}
}
out.WriteString(strings.Repeat(" ", depth))
out.WriteString(sel)
out.WriteString(" {\n")
depth++
case '}':
flushDecl(false)
depth--
if depth < 0 {
return Result{Error: errUnbalancedBrace}
}
out.WriteString(strings.Repeat(" ", depth))
out.WriteString("}\n")
case ';':
flushDecl(true)
default:
buf.WriteByte(css[i])
}
}
if depth != 0 {
return Result{Error: errUnclosedBlock}
}
flushDecl(false)
return Result{Output: unmask(out.String(), strs)}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →