#!/usr/bin/env python
from os import environ
import os.path
if 'relpath' not in dir(os.path):
from posixpath import curdir, abspath, sep, commonprefix, pardir, join
def relpath(path, start=curdir):
# From the 2.6.4 posixpath.py
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
os.path.relpath = relpath
os.path.sep = '/'
def crumbs(uri, root_directory):
"""
>>> crumbs('/path/to/directory/', root_directory='/path/')
(['home', 'to'], '../')
>>> crumbs('/path/to/directory/index.html', root_directory='/path/')
(['home', 'to'], '../')
>>> crumbs('/path/to/directory/page', root_directory='/path/')
(['home', 'to', 'directory'], './')
"""
if uri.endswith(os.path.sep):
uri += 'index.html'
uri_dir = os.path.dirname(uri)
root_dir = os.path.abspath(os.path.join(uri_dir, root_directory))
relpath = os.path.relpath(uri, start=root_dir)
dirs = relpath.split(os.path.sep)
if dirs[-1].startswith('index.'):
dirs.pop(-1)
parent = '../'
else:
parent = './'
dirs.insert(0, 'home')
dirs.pop(-1) # don't display a breadcrumb for the current page
return (dirs, parent)
def href(index, dirs, parent):
"""
>>> href(0, ['home', 'to'], '../')
'../..'
>>> href(1, ['home', 'to'], '../')
'../'
>>> href(0, ['home', 'to', 'directory'], './')
'./../..'
>>> href(1, ['home', 'to', 'directory'], './')
'./..'
>>> href(2, ['home', 'to', 'directory'], './')
'./'
"""
level = len(dirs) - index - 1
return os.path.join(parent, *(['..']*level))
def name(directory):
"""
Convert lowercase directory names to title case.
>>> name('funky_name')
'Funky Name'
Leave pre-capitalized names alone.
>>> name('FunKy_Name')
'FunKy Name'
"""
directory = directory.replace('_', ' ')
if directory == directory.lower():
directory = directory.title()
return directory
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
import sys
if len(sys.argv) > 1 and sys.argv[1] == '--test':
test()
sys.exit(0)
error = None
try:
dirs,parent = crumbs(environ['DOCUMENT_URI'],
environ['root_directory'])
except Exception, error:
if False: # for testing/debugging
raise
print 'Content-type: text/html; Charset=UTF-8;\n'
if error:
print '
'
print 'DOCUMENT_URI\n', environ['DOCUMENT_URI']
print '\nroot_directory\n', environ['root_directory']
print '\nError:\n', error
print '
'
else:
print ' > '.join(['
%s' % (href(i, dirs, parent), name(d))
for i,d in enumerate(dirs)])