about summary refs log tree commit diff stats
path: root/plugins/minimize.sh
blob: f7eec1bd719db3d4233b597eb5ec6c7a8c53320d (plain)
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
# minimize.sh --- Minimize CSS/JS assets using sed

# from https://www.tero.co.uk/scripts/minify.php

### Commentary:

## How it works
# It removes comments from CSS and Javascript files using sed. First it replaces
# /**/ and /*\*/ with /~~/ and /~\~/ as these comments are used as CSS hacks and
# should stay in the file. Then it removes /*...*/ style comments on single
# lines (from Javascript and CSS files - this was adapted from a common PHP
# regular expression for removing CSS comments). Then it removes // style
# comments from Javascript files (unless they are preceded by a : which means
# they might be web links). (It's done in this order so that comments like
# /*...//...*/ get removed properly). Then it replaces all newlines with spaces
# and removes /*...*/ style comments again (this time over multiple lines). Then
# it puts the /**/ and /*\*/ CSS hacks back in. Then it replaces multiple spaces
# with single spaces. Then it removes spaces before [{;:,] and then spaces after
# [{:;,].

## Problems - quotes and Ajaxy functions
# This script does not ignore things in quotes. So if you have a comment
# inside a quote in a Javascript file, such as document.writeln ('//This
# is a comment');, the script will remove everything from the // and
# cause a Javascript error. Also, all lines of Javascript must end with
# a semicolon. This can be an issue with libraries which declare
# functions on a line but don't end the line with a semicolon (as is
# common in Ajax and JQuery scripts). For example, in: load : function
# (url,callback,format) {...} http.send(nul);, there should be a
# semicolon after the function definition. This is legal Javascript if
# there's a line break, but causes an error once minimised without the
# line break.

## The Function
minimize() { # minimize < INPUT
    sed -e "s|/\*\(\\\\\)\?\*/|/~\1~/|g" \
        -e "s|/\*[^*]*\*\+\([^/][^*]*\*\+\)*/||g" \
        -e "s|\([^:/]\)//.*$|\1|" -e "s|^//.*$||" |
        tr '\n' ' ' |
        sed -e "s|/\*[^*]*\*\+\([^/][^*]*\*\+\)*/||g" \
            -e "s|/\~\(\\\\\)\?\~/|/*\1*/|g" \
            -e "s|\s\+| |g" \
            -e "s| \([{;:,]\)|\1|g" \
            -e "s|\([{;:,]\) |\1|g"
}