-
Notifications
You must be signed in to change notification settings - Fork 5
/
minify.awk
90 lines (86 loc) · 2.56 KB
/
minify.awk
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
BEGIN { Q = "'" }
/^BEGIN/ { in_begin = 1 }
in_begin && /^}/ { in_begin = 0 }
in_begin && $1 ~ /^delete/{ next }
{ minifyLine() }
function minifyLine( l,subs) {
if (!/"#"/ && !/\*#\// && !/\*\(#/) gsub("[ \t\r\n]*#.*$", "")
gsub(/ == /, "==")
gsub(/ = /, "=")
gsub(/ != /, "!=")
gsub(/ >= /, ">=")
gsub(/ <= /, "<=")
gsub(/; +/, ";")
gsub(/ ~ /, "~")
gsub(/ !~ /, "!~")
gsub(/ \+= /, "+=")
gsub(/ > /, ">")
gsub(/ < /, "<")
gsub(/ \/ /, "/")
gsub(/ \* /, "*")
gsub(/ \+ /, "+")
gsub(/ \|\| */, "||")
gsub(/ \| /, "|")
if (/ \? /) gsub(/ : /, ":")
gsub(/ \? /, "?")
gsub(/if \(/, "if(")
gsub(/for \(/, "for(")
gsub(/while \(/, "while(")
gsub(/ && /, "\\&\\&")
gsub(/[)] [{]/, "){")
gsub(/\( +/, "(")
gsub(/[{] +/, "{")
gsub(/} +/, "}")
gsub(/[)] +/, ")")
gsub(/print +"/, "print\"")
gsub(/printf +"/, "printf\"")
if (!/^ +}/) gsub(/ +}/, "}")
subs[", +"] = ","
subs[" *- "] = "-"
subs["] +"] = "]"
subs["^ +in "] = "in "
subs[" +$"] = ""
gsubKeepStrings(subs)
gsub(Q, Q "\\" Q Q)
if (l = trim($0)) { decreaseIndent(); printf "%s", (l == "}" ? l : (NR == 1 ? "" : "\n") $0) }
}
function decreaseIndent() {
match($0, /^ */)
$0 = sprintf("%" (RLENGTH - 1) / 2 "s", "") substr($0, RLENGTH)
}
function gsubKeepStrings(subs, nonString,s,isString,i,c,regex) {
nonString = ""
s = ""
isString = 0
for (i=1;(c=substr($0,i,1))!="";i++) {
# print "> " i " " c
if ("\"" == c && (substr($0,i-1,1) != "\\" || substr($0,i-2,1) == "\\")) {
if (!isString) {
for (regex in subs)
gsub(regex, subs[regex], nonString)
s = s nonString
nonString = ""
} else {
# skip whitespaces after "
while (substr($0,i+1,1) == " ") i++
}
s = s c # append this "
isString = !isString
} else if (isString) {
s = s c
} else {
nonString = nonString c
}
}
for (regex in subs)
gsub(regex, subs[regex], nonString)
s = s nonString
$0 = s
}
function trim(s) { sub(/^[ \t\r\n]+/, "", s); sub(/[ \t\r\n]+$/, "", s); return s }
#BEGIN { $0 = "aaa\"aaa\"bbbaaa"; gsubKeepStrings("aaa","AAA"); print }
#BEGIN { $0 = "aaa\"aaa\\\"aaa\"bbbaaa"; gsubKeepStrings("aaa","AAA"); print }
#BEGIN { $0 = "if (\"-h\" in Args || \"--help\" in Args) {"; gsubKeepStrings("^ +in", "in"); print }
#BEGIN { $0 = " if (arg == \"-f\" || arg == \"--file\") {"; minifyLine() }
#BEGIN { $0 = " res = dayS \" \" (hrS == \"\" ? \"0 h\" : hrS)"; minifyLine() }
#BEGIN { $0 = " quicksort(GlobFiles, 0, arrLen(GlobFiles) - 1)"; minifyLine() }