#!/usr/bin/env python
#coding: utf-8
#
# Bobbi - Peter Hopcroft, February 2014.
#
# input variables: Input: a css for the website html
# DropboxPath: variable must exist
# output variables: Output: the html for the website
# DropboxPath: relative path to write html in Dropbox
import codecs
import console
import editor
import functools
import glob
import markdown
import os
import urllib
import workflow
# template for a post, markdown ----------
TPOST = """
<div id="{Tlink}"></div>
{Ttext}
-----
"""
# template for the webpage body, markdown ----------
TBODY = """# {Tname}
{Ttoc}
-----
{Tposts}
</body>
</html>
"""
# template for the webpage, html ----------
TPAGE = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{Ttitle}</title>
<style type="text/css">
{Tcss}
</style>
</head>
<body>
{Tbody}
</body>
</html>
"""
# template for a message to user ----------
TMSG = """
Website name: {Tsite}
Dropbox path to write html to:
{Tdbp}
Names of post files, in order:
{Tnames}
"""
# end of templates ----------
MARKDOWN_EXT = '.md'
DROPBOX_MARK = '/Dropbox/'
def split_dpfe(full_path):
d, f_e = os.path.split(full_path)
x, p = os.path.split(d)
f, e = os.path.splitext(f_e)
return d, p, f, e # directory, parent, file name, extension
console.clear()
css = workflow.get_input()
# get current file data
ed, ep, ef, ee = split_dpfe(editor.get_path())
page_name = urllib.quote(ep) # website name is parent folder
if (ee != MARKDOWN_EXT) or (not DROPBOX_MARK in ed):
console.alert ('You need a markdown file open in your Dropbox folder of posts')
else:
# get markdown post files
md_files = glob.glob(os.path.join(ed, '*' + MARKDOWN_EXT))
md_files.sort (key=os.path.getmtime, reverse=True) # newest first
# accumulate the posts, toc and names
posts = ''
toc = '| '
names = '| '
for md_file in md_files:
d, p, f, e = split_dpfe(md_file)
link = urllib.quote(f) # link name = file name
toc += '[' + f + '](#' + link + ') | ' # a markdown link
with codecs.open(md_file, 'r', 'utf-8') as mf:
text = mf.read()
posts += TPOST.format (Tlink = link, Ttext = text) # post template
names += f + ' | '
# make the html
body = TBODY.format (Tname=page_name, Ttoc=toc, Tposts=posts)
body = markdown.markdown(body, extensions=['tables'])
page = TPAGE.format (Tcss=css, Ttitle=page_name, Tbody=body)
# get dropbox path to write html to
x, dr, pa = ed.partition (DROPBOX_MARK)
dbp = os.path.join(pa, page_name + '.html')
# set output variables
# ideally we would use editor.set_file_contents here, but it has a bug
workflow.set_variable('DropboxPath', dbp)
workflow.set_output(page)
# say what is happening, can cancel this
msg = TMSG.format (Tsite=page_name, Tdbp=dbp, Tnames=names) # msg template
console.alert('Ready to write html to Dropbox', msg, 'OK')
There are no comments yet.