Created
July 2, 2011 12:33
-
-
Save pda/1059988 to your computer and use it in GitHub Desktop.
bundlua: CSS/JavaScript bundler for lighttpd mod_magnet (from 2007)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- bundlua: a css/javascript bundler written in LUA for lighttpd's mod_magnet | |
-- Paul Annesley : paul@annesley.cc : 2007-02-12 | |
-- URL format: /bundle/file1.css,file2.css | |
-- include trailing slash for directories | |
local urlPrefix = '/bundle/' | |
local basedir = '/path/to/htdocs/' | |
local cssDir = basedir .. 'css/' | |
local jsDir = basedir .. 'js/' | |
local cacheDir = '/path/to/cache/dir/' | |
local requestPath = lighty.env['uri.path'] | |
if (string.find(requestPath, urlPrefix, 1, true) == 1) then | |
local cacheHit = false | |
local fileString = string.sub(requestPath, string.len(urlPrefix)+1) | |
-- determine content type | |
if (string.sub(fileString, -4) == '.css') then | |
srcDir = cssDir | |
elseif (string.sub(fileString, -3) == '.js') then | |
srcDir = jsDir | |
else | |
return 404 | |
end | |
-- get list of existing files and most recent mtime | |
local requestFilenames = {} | |
local lastMod = 0 | |
for name in string.gmatch(fileString, '%w[%w%-%_]*%.%w%w%w?') do | |
local fileStat = lighty.stat(srcDir .. name) | |
if (fileStat) then | |
local mtime = fileStat.st_mtime | |
if (mtime > lastMod) then lastMod = mtime end | |
table.insert(requestFilenames, name) | |
end | |
end | |
-- 404 if no files | |
if (# requestFilenames == 0) then return 404 end | |
-- check for a cache hit | |
local bundleFile = cacheDir .. lastMod .. '-' .. fileString | |
local bundleStat = lighty.stat(bundleFile) | |
if (bundleStat and lastMod <= bundleStat.st_mtime) then cacheHit = true end | |
if (cacheHit == false) then | |
-- bundle files | |
local outHandle = io.open(bundleFile, 'w+') | |
if (outHandle) then | |
outHandle:write("/* bundlua @ " .. os.date('%Y-%m-%d %T') .. " */\n\n") | |
for i,name in ipairs(requestFilenames) do | |
local path = srcDir .. name | |
local inHandle = io.open(path) | |
if (inHandle) then | |
outHandle:write("/* --- " .. name .. " --- */\n") | |
outHandle:write(inHandle:read('*a') .. "\n") | |
io.close(inHandle) | |
else | |
print('Unable to open ' .. path .. ' for reading') | |
end | |
end | |
outHandle:flush() | |
io.close(outHandle) | |
else | |
print('Unable to open ' .. bundleFile .. ' for writing') | |
end | |
end | |
-- tell lighttpd where it's at | |
lighty.env["physical.path"] = bundleFile | |
lighty.env["physical.doc-root"] = cacheDir | |
lighty.env["physical.rel-path"] = '/' .. fileString | |
lighty.header['X-Bundlua-Cache-Hit'] = tostring(cacheHit) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment