Skip to content

Instantly share code, notes, and snippets.

@Donearm
Created June 2, 2013 07:42
Show Gist options
  • Save Donearm/5692939 to your computer and use it in GitHub Desktop.
Save Donearm/5692939 to your computer and use it in GitHub Desktop.
Quick and simple Markdown to Html conversion for my extremely raw personal wiki
#!/usr/bin/env lua
---
-- @author Gianluca Fiore
-- @copyright 2013, Gianluca Fiore <forod.g@gmail.com>
--
package.path = "/mnt/d/Script/lib/?.lua;" .. package.path
local markdown = require("markdown") -- that's the markdown.lua implementation from http://www.frykholm.se/files/markdown.lua
local lfs = require("lfs")
local html_header1 = [[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>]]
local html_header2 = [[</title>
<link rel="stylesheet" type="text/css" href="file:///mnt/d/Script/lib/markdown.css" />
<link rel="stylesheet" type="text/css" media="pring" href="file:///mnt/d/Script/lib/markdown-print.css" />
</head>
<body>
]]
local html_footer = [[</body></html>]]
---Function equivalent to POSIX basename
--@param str a string
function basename(str)
local name = string.gsub(str, "(.*/)(.*)", "%2")
return name
end
---Returns only the filename stripping the extension
--@param str a filename complete with extension
function filename(str)
local name = string.gsub(str, "(.*)%.(.*)", "%1")
return name
end
---Convert a markdown file to one with the same name but in html
--@param file the file to convert
function mkdtohtml(file)
local f = assert(io.open(file, "r"), "couldn't open file")
local n = filename(basename(file))
local html_filename = n .. '.html' -- we need this string to check
-- against "file" when comparing modification times
-- Compare modification time of the markdown and html files. Write a
-- new html file only for the changed files
local mdtime = lfs.attributes(file, "modification")
local htmltime = lfs.attributes(html_filename, "modification")
if mdtime > htmltime then
-- the markdown file has been modified after the last creation
-- of the corresponding html. Update it!
local html_file = io.open(n .. '.html', "w")
html_file:write(html_header1)
html_file:write(html_header2)
html_file:write(markdown(f:read("*a")))
html_file:write(html_footer)
html_file:close()
end
f:close()
end
if not arg[1] then
print("No file given, exiting...")
os.exit(1)
else
mkdtohtml(arg[1])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment