minify/squish.minify.lua

changeset 1
2d9fe676e684
child 5
6ed9037f4a15
equal deleted inserted replaced
0:b119b560ca3d 1:2d9fe676e684
1 local optlex = require "optlex"
2 local optparser = require "optparser"
3 local llex = require "llex"
4 local lparser = require "lparser"
5
6 local minify_defaults = {
7 none = {};
8 default = { "comments", "whitespace", "emptylines", "numbers", "locals" };
9 basic = { "comments", "whitespace", "emptylines" };
10 maximum = { "comments", "whitespace", "emptylines", "eols", "strings", "numbers", "locals", "entropy" };
11 }
12 minify_defaults.full = minify_defaults.maximum;
13
14 for _, opt in ipairs(minify_defaults[opts.minify_level or "default"] or {}) do
15 opts["minify_"..opt] = true;
16 end
17
18 local option = {
19 ["opt-locals"] = opts.minify_locals;
20 ["opt-comments"] = opts.minify_comments;
21 ["opt-entropy"] = opts.minify_entropy;
22 ["opt-whitespace"] = opts.minify_whitespace;
23 ["opt-emptylines"] = opts.minify_emptylines;
24 ["opt-eols"] = opts.minify_eols;
25 ["opt-strings"] = opts.minify_strings;
26 ["opt-numbers"] = opts.minify_numbers;
27 }
28
29 local function die(msg)
30 print("LuaSrcDiet: "..msg); os.exit()
31 end
32
33 local function load_file(fname)
34 local INF = io.open(fname, "rb")
35 if not INF then die("cannot open \""..fname.."\" for reading") end
36 local dat = INF:read("*a")
37 if not dat then die("cannot read from \""..fname.."\"") end
38 INF:close()
39 return dat
40 end
41
42 local function save_file(fname, dat)
43 local OUTF = io.open(fname, "wb")
44 if not OUTF then die("cannot open \""..fname.."\" for writing") end
45 local status = OUTF:write(dat)
46 if not status then die("cannot write to \""..fname.."\"") end
47 OUTF:close()
48 end
49
50
51 function minify(srcfl, destfl)
52 local z = load_file(srcfl)
53 llex.init(z)
54 llex.llex()
55 local toklist, seminfolist, toklnlist
56 = llex.tok, llex.seminfo, llex.tokln
57 if option["opt-locals"] then
58 optparser.print = print -- hack
59 lparser.init(toklist, seminfolist, toklnlist)
60 local globalinfo, localinfo = lparser.parser()
61 optparser.optimize(option, toklist, seminfolist, globalinfo, localinfo)
62 end
63 optlex.print = print -- hack
64 toklist, seminfolist, toklnlist
65 = optlex.optimize(option, toklist, seminfolist, toklnlist)
66 local dat = table.concat(seminfolist)
67 -- depending on options selected, embedded EOLs in long strings and
68 -- long comments may not have been translated to \n, tack a warning
69 if string.find(dat, "\r\n", 1, 1) or
70 string.find(dat, "\n\r", 1, 1) then
71 optlex.warn.mixedeol = true
72 end
73 -- save optimized source stream to output file
74 save_file(destfl, dat)
75 end
76
77 print_info("Minifying "..out_fn.."...");
78 minify(out_fn, out_fn);

mercurial