util.lua (2004B)
1 local date = require "date" 2 local path = require "path" 3 4 function die(err, msg, ...) 5 msg = tostring(msg or err) 6 if err then 7 io.stderr:write(string.format(msg .. "\n", ...)) 8 os.exit(1) 9 end 10 end 11 12 function maildate(s) 13 local d = date(s) 14 local sec = date.diff(d, date.epoch()):spanseconds() 15 return sec 16 end 17 18 function yn(prompt) 19 meaning = {Y = true, y = true, n = false, N = false} 20 while meaning[ans] == nil do 21 io.write(prompt) 22 io.flush() 23 ans = io.read(1) 24 end 25 return meaning[ans] 26 end 27 28 function decodewith(decoder, fn) 29 die(not path.exists(fn), fn.." does not exist.") 30 die(not path.isfile(fn), fn.." is not a file.") 31 local f, err = io.open(fn, "r") 32 die(err) 33 status, res = xpcall(decoder, die, f:read("a")) 34 f:close() 35 die(not status, res) 36 return res 37 end 38 39 function encodewith(encoder, fn, data) 40 local f, err = io.open(fn, "w") 41 die(not status, err) 42 status, err = f:write(encoder(data)) 43 die(not status, err) 44 end 45 46 function format(fmt, dict, sett) 47 -- A identifier is 48 -- > any string of Latin letters, Arabic-Indic digits, and 49 -- > underscores, not beginning with a digit and not being a reserved 50 -- > word 51 52 -- local reserved = { 53 -- "and", "break", "do", "else", "elseif", "end", "false", "for", 54 -- "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", 55 -- "return", "then", "true", "until", "while" 56 -- } 57 res = fmt 58 for s in string.gmatch(fmt, "%{([_a-zA-Z][._a-zA-Z0-9]*)%}") do 59 local value = dict 60 local pref = sett 61 for k in string.gmatch(s, "([_a-zA-Z][_a-zA-Z0-9]*)") do 62 if type(value) == "table" then value = value[k] end 63 if type(pref) == "table" then pref = pref[k] end 64 end 65 if pref and value then string.format(pref, value) end 66 res = fmt.gsub(res, "{"..s.."}", value or "nil") 67 end 68 return res 69 end 70 71 function unix2week(s) 72 return os.date("%GW%V", s) 73 end 74 75 function prevweek(w) 76 return date.diff(date(w):adddays(-7), date.epoch()):spanseconds() 77 end