aboutsummaryrefslogtreecommitdiff
path: root/common/file.lua
blob: 5b5ebedbd2d9a1e9b64a52aa6ad80ba9d82ec859 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
file = {}

local mdroot = "/usr/local/apache2/htdocs"

function string.split(self, sep)
	if not sep then sep = "%s" end

	local t = {}
	for match in (self .. sep):gmatch("(.-)" .. sep) do
		table.insert(t, match)
	end

	return t
end

function file.read(path)
	local f = io.open(path, "r")
	if not f then
		return nil
	end

	local contents = f:read("*a")
	f:close()

	return contents
end

function file.write(path, contents)
	local f = io.open(path, "w")
	if not f then
		return false
	end

	f:write(contents)
	f:close()

	return true
end

function file.process(uri, templates, params)
	path = mdroot .. uri

	local contents = file.read(path)
	if not contents then
		return nil
	end

	if templates then
		for template, value in pairs(templates) do
			contents = contents:gsub("%${" .. template .. "}", value)
		end
	end

	local filename = os.tmpname()
	file.write(filename, contents)

	params = (params or ""):match("^([%a%d-=]*)$") or ""

	local static_params = '--css /common.css -f markdown --standalone '
	local cmd = 'pandoc ' .. params .. ' ' .. static_params .. ' ' .. filename
	local handle = io.popen(cmd)
	local html = handle:read("*a")
	handle:close()

	return html
end

return file