master build.lua
  1#!/usr/bin/env lua
  2
  3local sDir = (function()
  4  local d = debug.getinfo(1, "S").source:sub(2):match("^(.*)/[^/]+$")
  5  if d then return d .. "/" end
  6  return "./"
  7end)()
  8
  9package.cpath = package.cpath .. ";" .. sDir .. "/lib/?.so"
 10package.path = package.path .. ";" .. sDir .. "/lib/?.lua"
 11
 12local lfs = require("lfs")
 13local mk = require("markdown")
 14
 15local cfg, buf = {}, {}
 16local chg = false
 17local exp = {}
 18
 19local lg = function(msg) table.insert(buf, msg) end
 20
 21local er = function(msg)
 22  io.stderr:write(":: [error] " .. msg .. "\n")
 23  os.exit(1)
 24end
 25
 26local ePath = function(p)
 27  if p:sub(1, 1) == "~" then return (os.getenv("HOME") or "") .. p:sub(2)
 28  elseif p:sub(1, 1) == "/" then return p
 29  else return sDir .. p end
 30end
 31
 32local sub = function(s, vars)
 33  return s:gsub("{(%u+)}", function(k)
 34    if vars[k] ~= nil then return tostring(vars[k]) end
 35    return "{" .. k .. "}"
 36  end)
 37end
 38
 39local gSex = function(expr, env)
 40  local cunt = "return " .. expr
 41  local fn
 42  if setfenv and loadstring then
 43    fn = loadstring(cunt)
 44    if fn then setfenv(fn, env or {}) end
 45  else
 46    fn = load(cunt, "expr", "t", env or {})
 47  end
 48  if not fn then return nil end
 49  local ok, res = pcall(fn)
 50  if ok and res ~= nil then return tostring(res) end
 51  return nil
 52end
 53
 54local mDir = function(path)
 55  path = path:gsub("/+$", "")
 56  local cur = ""
 57  if path:sub(1, 1) == "/" then
 58    cur = "/"
 59    path = path:sub(2)
 60  end
 61  for p in path:gmatch("[^/]+") do
 62    cur = cur .. p .. "/"
 63    if lfs.attributes(cur, "mode") ~= "directory" then lfs.mkdir(cur) end
 64  end
 65end
 66
 67local rFile = function(path)
 68  local f = io.open(path, "r")
 69  if not f then return nil end
 70  local cnt = f:read("*a")
 71  f:close()
 72  return cnt
 73end
 74
 75local sCheck = function(path, cnt)
 76  local sz = lfs.attributes(path, "size")
 77  if sz ~= #cnt then return false end
 78  local f = io.open(path, "rb")
 79  if not f then return false end
 80  local existing = f:read("*a")
 81  f:close()
 82  return existing == cnt
 83end
 84
 85local wFile = function(path, cnt, srcPath)
 86  if sCheck(path, cnt, srcPath) then return false end
 87  local par = path:match("^(.*)/[^/]+$")
 88  if par and par ~= "" then mDir(par) end
 89  local f = io.open(path, "w")
 90  if not f then er("cannot write " .. path) end
 91  f:write(cnt)
 92  f:close()
 93  return true
 94end
 95
 96local mn = function()
 97  local cPath = sDir .. "config.lua"
 98  local chk, eMsg = loadfile(cPath)
 99  if not chk then er("cant load " .. (eMsg or "?")) end
100  for k, v in pairs(chk()) do cfg[k] = v end
101
102  local rsv
103  rsv = function(val, seen)
104    if type(val) ~= "string" then return val end
105    return val:gsub("{(%u+)}", function(name)
106      if seen[name] then return "{" .. name .. "}" end
107      local v = cfg[name]
108      if v == nil then return "{" .. name .. "}" end
109      local nSeen = {}
110      for k in pairs(seen) do nSeen[k] = true end
111      nSeen[name] = true
112      return tostring(rsv(v, nSeen))
113    end)
114  end
115  for k, v in pairs(cfg) do cfg[k] = rsv(v, {}) end
116
117  cfg.NAVIGNORE = cfg.NAVIGNORE or {}
118  local navIgs = {}
119  for _, v in ipairs(cfg.NAVIGNORE) do navIgs[v] = true end
120  local navIgn = function(n) return navIgs[n] == true end
121
122  cfg.IGNORE = cfg.IGNORE or {}
123  local igs = {}
124  for _, v in ipairs(cfg.IGNORE) do igs[v] = true end
125  local ign = function(n) return igs[n] == true end
126
127  cfg.INPUT = ePath(cfg.INPUT):gsub("/+$", "")
128  cfg.OUTPUT = ePath(cfg.OUTPUT):gsub("/+$", "")
129
130  local tpl = rFile(cfg.INPUT .. "/template.html")
131  local cfgM = lfs.attributes(cPath, "modification") or 0
132  local mdM = lfs.attributes(sDir .. "/lib/markdown.lua", "modification") or 0
133  local tplM = lfs.attributes(cfg.INPUT .. "/template.html", "modification") or 0
134  local incM = 0
135  for incPath in tpl:gmatch('{{%s*include%s+"([^"]+)"%s*}}') do
136    local m = lfs.attributes(cfg.INPUT .. "/" .. incPath, "modification") or 0
137    if m > incM then incM = m end
138  end
139
140  local navM = 0
141  local pMts
142  pMts = function(dir)
143    for name in lfs.dir(dir) do
144      if name ~= "." and name ~= ".." and not ign(name) then
145        local f = dir .. "/" .. name
146        if lfs.attributes(f, "mode") == "directory" then
147          pMts(f)
148        elseif name:match("%.md$") then
149          local m = lfs.attributes(f, "modification") or 0
150          if m > navM then navM = m end
151        end
152      end
153    end
154  end
155  pMts(cfg.INPUT)
156
157  local stale = false
158  local pStale
159  pStale = function(dir)
160    for name in lfs.dir(dir) do
161      if name ~= "." and name ~= ".." and not ign(name) then
162        local p = dir .. "/" .. name
163        local mode = lfs.attributes(p, "mode")
164        if mode == "directory" then
165          pStale(p)
166        elseif mode == "file" and name:match("%.html$") then
167          local rel = p:sub(#cfg.OUTPUT + 2)
168          local src = cfg.INPUT .. "/" .. rel
169          local sMode = lfs.attributes(src, "mode")
170          local sMd = lfs.attributes(src:gsub("%.html$", ".md"), "mode")
171          if sMode ~= "file" and sMd ~= "file" then stale = true end
172        end
173      end
174    end
175  end
176  if lfs.attributes(cfg.OUTPUT, "mode") == "directory" then pStale(cfg.OUTPUT) end
177
178  local attrCache = {}
179  local attrGet = function(path, mode)
180    local key = path .. "\0" .. mode
181    local v = attrCache[key]
182    if v == nil then
183      v = lfs.attributes(path, mode)
184      if v == nil then v = false end
185      attrCache[key] = v
186    end
187    if v == false then return nil end
188    return v
189  end
190
191  mDir(cfg.OUTPUT)
192
193  lg(":: copying el files from " .. cfg.INPUT)
194  local tRender
195  local cFiles
196  cFiles = function(dir)
197    for name in lfs.dir(dir) do
198      if name ~= "." and name ~= ".." and not ign(name) then
199        local f = dir .. "/" .. name
200        local mode = lfs.attributes(f, "mode")
201        if mode == "directory" then
202          cFiles(f)
203        elseif mode == "file" then
204          if not (name:match("%.md$") or f:match("/template%.html$")) then
205            local rel = f:sub(#cfg.INPUT + 2)
206            local dst = cfg.OUTPUT .. "/" .. rel
207            exp[dst] = true
208            local cnt = rFile(f)
209            if name:match("%.html$") then
210              local srcM = lfs.attributes(f, "modification") or 0
211              cnt = tRender(cnt, { MTIME = srcM })
212            end
213            if wFile(dst, cnt) then
214              chg = true
215              lg("copied " .. dst)
216            end
217          end
218        end
219      end
220    end
221  end
222  cFiles(cfg.INPUT)
223
224  local pCond
225  pCond = function(s, vars)
226    local fEnd = function(s, sPos)
227      local dpt = 1
228      local pos = sPos
229      while pos <= #s do
230        local tStart = s:find("{{", pos, true)
231        if not tStart then return nil end
232        local tEnd = s:find("}}", tStart, true)
233        if not tEnd then return nil end
234        local tag = s:sub(tStart + 2, tEnd - 1):gsub("^%s+", ""):gsub("%s+$", "")
235        if tag:match("^if%s") then dpt = dpt + 1
236        elseif tag == "end" then
237          dpt = dpt - 1
238          if dpt == 0 then return tStart, tEnd + 2 end
239        end
240        pos = tEnd + 2
241      end
242      return nil
243    end
244
245    local out, pos = {}, 1
246    while pos <= #s do
247      local tStart = s:find("{{", pos, true)
248      if not tStart then
249        table.insert(out, s:sub(pos))
250        break
251      end
252      table.insert(out, s:sub(pos, tStart - 1))
253      local tEnd = s:find("}}", tStart, true)
254      if not tEnd then
255        table.insert(out, s:sub(tStart))
256        break
257      end
258      local tag = s:sub(tStart + 2, tEnd - 1):gsub("^%s+", ""):gsub("%s+$", "")
259      if tag:match("^if%s") then
260        local cond = tag:match("^if%s+(.+)$")
261        local mStart, mEnd = fEnd(s, tEnd + 2)
262        if not mStart then pos = tEnd + 2
263        else
264          local body = s:sub(tEnd + 2, mStart - 1)
265          local neg, var = cond:match("^not%s+(.+)$")
266          if not neg then var = cond end
267          local val = vars[var]
268          local tru = (val ~= nil and val ~= "" and val ~= false)
269          if neg then tru = not tru end
270          if tru then table.insert(out, pCond(body, vars)) end
271          pos = mEnd
272        end
273      else
274        table.insert(out, "{{" .. tag .. "}}")
275        pos = tEnd + 2
276      end
277    end
278    return table.concat(out, "")
279  end
280
281  tRender = function(txt, vars)
282    txt = txt:gsub('{{%s*include%s+"([^"]+)"%s*}}', function(path)
283      local full
284      if path:sub(1, 1) == "/" then full = path else full = cfg.INPUT .. "/" .. path end
285      local c = rFile(full)
286      
287      if not c and path:match("%.html$") then
288        c = rFile(full:gsub("%.html$", ".md"))
289        if c then c = mk(c) end
290      elseif c and path:match("%.md$") then
291        c = mk(c)
292      elseif c and path:match("%.lua$") then
293        local env = {}
294        for k, v in pairs(_G) do env[k] = v end
295        for k, v in pairs(cfg) do env[k] = v end
296        for k, v in pairs(vars) do env[k] = v end
297        c = gSex("(function()\n" .. c .. "\nend)()", env)
298      end
299      
300      if c then return tRender(c, vars) end
301      return ""
302    end)
303
304    txt = pCond(txt, vars)
305
306    local env = {}
307    for k, v in pairs(_G) do env[k] = v end
308    for k, v in pairs(cfg) do env[k] = v end
309    for k, v in pairs(vars) do env[k] = v end
310
311    txt = txt:gsub("{{%s*(.-)%s*}}", function(expr)
312      if vars[expr] ~= nil then return tostring(vars[expr]) end
313      if cfg[expr] ~= nil then return tostring(cfg[expr]) end
314      return gSex(expr, env) or ""
315    end)
316
317    return txt
318  end
319
320  local bNav
321  bNav = function(cur)
322    local fLabel = function(r, t)
323      local l
324      if "/" .. r == cur then
325        if cfg.LINKCURR:find("{CURR}", 1, true) then l = cfg.LINKCURR:gsub("{CURR}", function() return t end) else l = cfg.LINKCURR .. t end
326        return '<a href="/' .. r .. '" class="aPage"><span class="aIndicator">' .. l .. '</span></a>'
327      end
328      if cfg.LINK:find("{CURR}", 1, true) then l = cfg.LINK:gsub("{CURR}", function() return t end) else l = cfg.LINK .. t end
329      return '<a href="/' .. r .. '">' .. l .. '</a>'
330    end
331
332    local pDir
333    pDir = function(dir)
334      local out, nms = {}, {}
335      for name in lfs.dir(dir) do 
336        if name ~= "." and name ~= ".." and not ign(name) and not navIgn(name) then 
337          table.insert(nms, name) 
338        end 
339      end
340      table.sort(nms)
341
342      for _, name in ipairs(nms) do
343        local itm = dir .. "/" .. name
344        local mode = attrGet(itm, "mode")
345        if mode == "file" and name:match("%.md$") then
346          if name ~= "index.md" then
347            table.insert(out, '<li>' .. fLabel(itm:sub(#cfg.INPUT + 2):gsub("%.md$", ".html"), name:gsub("%.md$", ""):gsub("-", " ")) .. '</li>')
348          end
349        elseif mode == "directory" then
350          local sub = pDir(itm)
351          if #sub > 0 then
352            table.insert(out, '<li>' .. name .. '/<ul>\n' .. table.concat(sub, "\n") .. '\n</ul></li>')
353          end
354        end
355      end
356
357      return out
358    end
359
360    return table.concat(pDir(cfg.INPUT), "\n")
361  end
362
363  local pMd
364  pMd = function(dir)
365    for name in lfs.dir(dir) do
366      if name ~= "." and name ~= ".." and not ign(name) then
367        local f = dir .. "/" .. name
368        local mode = lfs.attributes(f, "mode")
369        if mode == "directory" then
370          pMd(f)
371        elseif mode == "file" and name:match("%.md$") then
372          local rel = f:sub(#cfg.INPUT + 2):gsub("%.md$", ".html")
373          local dst = cfg.OUTPUT .. "/" .. rel
374          exp[dst] = true
375
376          local srcM = lfs.attributes(f, "modification") or 0
377          local maxM = srcM
378          if cfgM > maxM then maxM = cfgM end
379          if mdM > maxM then maxM = mdM end
380          if tplM > maxM then maxM = tplM end
381          if incM > maxM then maxM = incM end
382          if navM > maxM then maxM = navM end
383          local dstM = lfs.attributes(dst, "modification") or 0
384
385          if stale or not (dstM > 0 and dstM >= maxM) then
386            local rawr = rFile(f) or ""
387            local base = name:gsub("%.md$", "")
388            
389            local env = {}
390            for k, v in pairs(_G) do env[k] = v end
391            for k, v in pairs(cfg) do env[k] = v end
392            env.CURR = base
393            env.MTIME = srcM
394
395            rawr = rawr:gsub("{{%s*(.-)%s*}}", function(expr)
396              local inc = expr:match('^include%s+"([^"]+)"$')
397              if inc then return tRender('{{include "' .. inc .. '"}}', { CURR = base, MTIME = srcM }) end
398              if cfg[expr] ~= nil then return tostring(cfg[expr]) end
399              return gSex(expr, env) or ""
400            end)
401            local html = mk(rawr)
402
403            local cur = "/" .. rel
404            local pVars = { CURR = base }
405            local pFooter = sub(cfg.FOOTER, pVars)
406            
407            local pLinks = function(txt)
408              return txt:gsub("<a(.-)>(.-)</a>", function(attrs, inner)
409                if inner:find("<img", 1, true) or inner == "" then return "<a" .. attrs .. ">" .. inner .. "</a>" end
410                local href = attrs:match("href=['\"](.-)['\"]") or ""
411                local l
412                if (href == cur) or ("/" .. href == cur) then
413                  if cfg.LINKCURR:find("{CURR}", 1, true) then l = cfg.LINKCURR:gsub("{CURR}", function() return inner end) else l = cfg.LINKCURR .. inner end
414                  return '<a' .. attrs:gsub('class=["\'][^"\']*["\']', "") .. ' class="aPage"><span class="aIndicator">' .. l .. '</span></a>'
415                end
416                if cfg.LINK:find("{CURR}", 1, true) then l = cfg.LINK:gsub("{CURR}", function() return inner end) else l = cfg.LINK .. inner end
417                return '<a' .. attrs .. '>' .. l .. '</a>'
418              end)
419            end
420
421            html = pLinks(html)
422            pFooter = pLinks(pFooter)
423
424            local vars = { CURR = base, MTIME = srcM }
425            for k, v in pairs(cfg) do
426              if type(v) == "string" then vars[k] = sub(v, pVars)
427              elseif type(v) == "number" then vars[k] = tostring(v) end
428            end
429            vars.TITLE = sub(cfg.TITLE, pVars)
430            vars.NAV = "<ul>\n" .. bNav(cur) .. "\n</ul>"
431            vars.CONTENT = html
432            vars.FOOTER = pFooter
433            local out = tRender(tpl, vars)
434            if wFile(dst, out) then
435              chg = true
436              lg("wrote " .. dst)
437            end
438          end
439        end
440      end
441    end
442  end
443
444  pMd(cfg.INPUT)
445
446  local rem = {}
447  local rDel
448  rDel = function(dir)
449    local nms = {}
450    for name in lfs.dir(dir) do if name ~= "." and name ~= ".." then table.insert(nms, name) end end
451    for _, name in ipairs(nms) do
452      local p = dir .. "/" .. name
453      local lMode = lfs.symlinkattributes(p, "mode")
454      if lMode == "link" then
455        if not exp[p] then if os.remove(p) then table.insert(rem, p) end end
456      elseif lMode == "directory" then
457        rDel(p)
458        if lfs.rmdir(p) then table.insert(rem, p .. "/") end
459      elseif lMode == "file" then
460        if not exp[p] then if os.remove(p) then table.insert(rem, p) end end
461      end
462    end
463  end
464  rDel(cfg.OUTPUT)
465
466  if #rem > 0 then chg = true end
467  for _, p in ipairs(rem) do lg("removed " .. p) end
468
469  if chg then
470    for _, m in ipairs(buf) do print(m) end
471    print("build le done")
472    if cfg.AFTER then for _, cmd in ipairs(cfg.AFTER) do os.execute(rsv(cmd, {})) end end
473  else
474    print("no changes made; skipping el buildo")
475  end
476end
477
478mn()