| 1 | function gzip_file(infile_fn, outfile_fn) |
| 2 | local infile, err = io.open(infile_fn); |
| 3 | if not infile then |
| 4 | print_err("Can't open input file for reading: "..tostring(err)); |
| 5 | return; |
| 6 | end |
| 7 | |
| 8 | local outfile, err = io.open(outfile_fn..".gzipped", "wb+"); |
| 9 | if not outfile then |
| 10 | print_err("Can't open output file for writing: "..tostring(err)); |
| 11 | return; |
| 12 | end |
| 13 | |
| 14 | local data = infile:read("*a"); |
| 15 | infile:close(); |
| 16 | |
| 17 | local shebang, newdata = data:match("^(#.-\n)(.+)$"); |
| 18 | local code = newdata or data; |
| 19 | if shebang then |
| 20 | outfile:write(shebang) |
| 21 | end |
| 22 | |
| 23 | local file_with_no_shebang, err = io.open(outfile_fn..".pregzip", "wb+"); |
| 24 | if not file_with_no_shebang then |
| 25 | print_err("Can't open temp file for writing: "..tostring(err)); |
| 26 | return; |
| 27 | end |
| 28 | |
| 29 | file_with_no_shebang:write(code); |
| 30 | file_with_no_shebang:close(); |
| 31 | |
| 32 | local compressed = io.popen("gzip -c '"..outfile_fn..".pregzip'"); |
| 33 | code = compressed:read("*a"); |
| 34 | compressed:close(); |
| 35 | os.remove(outfile_fn..".pregzip"); |
| 36 | |
| 37 | local maxequals = 0; |
| 38 | code:gsub("(=+)", function (equals_string) maxequals = math.max(maxequals, #equals_string); end); |
| 39 | |
| 40 | outfile:write("local ungz = (function ()", require_resource "gunzip.lua", " end)()\n"); |
| 41 | |
| 42 | outfile:write[[return assert(loadstring((function (i)local o={} ungz{input=i,output=function(b)table.insert(o,string.char(b))end}return table.concat(o)end) ]]; |
| 43 | |
| 44 | --outfile:write [[return assert(loadstring(_gunzip]] |
| 45 | outfile:write((string.format("%q", code):gsub("\026", "\\026"))); |
| 46 | --outfile:write("[", string.rep("=", maxequals+1), "[", code, "]", string.rep("=", maxequals+1), "]"); |
| 47 | outfile:write(", '@", outfile_fn,"'))()"); |
| 48 | outfile:close(); |
| 49 | os.rename(outfile_fn..".gzipped", outfile_fn); |
| 50 | end |
| 51 | |
| 52 | if opts.gzip then |
| 53 | print_info("Gzipping "..out_fn.."..."); |
| 54 | gzip_file(out_fn, out_fn); |
| 55 | print_info("OK!"); |
| 56 | end |