__init__.py @ b9bf34a94aad

Send requests with empty path or non-markdown files to "file" command.
author Chris Eldredge <chris.eldredge@gmail.com>
date Fri, 10 Aug 2012 22:41:36 +0100
parents 1d3416da68e0
children c4e554f545cb
import os
import sys

# If using TortoiseHg, obtain Python-Markdown and tell Python where to find it:

import markdown
from mercurial.hgweb import webcommands, webutil, common
from mercurial import extensions, encoding, util
import logging

def filerevision_markdown(web, req, tmpl):
	path = webutil.cleanpath(web.repo, req.form.get('file', [''])[0])
	parts = os.path.splitext(path)

	if not parts[1] == '.markdown' and not parts[1] == '.md':
		return webcommands.file(web, req, tmpl)
	if not path:
		return webcommands.file(web, req, tmpl)
	previewMode = 'node' in req.form and req.form['node'][0] == '_preview'
	if previewMode:
		text = file(web.repo.root + "/" + path).read()
		fctx = webutil.filectx(web.repo, req)
		text = fctx.data()
	if util.binary(text):
		# todo: handle preview mode
		return rawfile(web, req, tmpl)

	md = markdown.Markdown(extensions=['wikilinks(base_url={0},end_url={1})'.format('', parts[1])])	
	html = md.convert(text)
	args = {'file':path,

	if previewMode:
		args.update({'rev':'PREVIEW', 'node':'PREVIEW'})

	return tmpl("markdown",	**args)

def summary_markdown(orig, web, req, tmpl):
	changeid = 'default' # todo: add hgrc config setting
	previewMode = False
	text = None
	cctx = web.repo[changeid]
	changeid = cctx.hex()[0:12]
	for filename in cctx:
		if filename.lower() == 'readme.md' or filename.lower() == 'readme.markdown':
			fctx = cctx.filectx(filename)
			text = fctx.data()
			readmefile = filename
	if text:
		ext = os.path.splitext(readmefile)[1]
		base_url = tmpl.defaults['url'] + 'markdown/' + changeid + "/"
		md = markdown.Markdown(
			extensions=['urlrebase', 'wikilinks'],
				'urlrebase' : [('base_url', base_url)],
				'wikilinks' : [('base_url', base_url), ('end_url', ext)]})
		readme = md.convert(text)
		readmefile = "ReadMe"
		readme = "Add ReadMe.md or ReadMe.markdown to this repository to display it here."
	tmpl.defaults['readmefilename'] = readmefile
	tmpl.defaults['readme'] = readme
	return orig(web, req, tmpl)

def find_working_copy_readme(repo):
	for filename in os.listdir(repo.root):
		if filename.lower() == 'readme.md' or filename.lower() == 'readme.markdown':
			return filename

def extsetup():
	extensions.wrapfunction(webcommands, 'summary', summary_markdown)
	webcommands.markdown = filerevision_markdown