"""Define a handler that generates an index for directories. Color scheme: http://colorschemedesigner.com/#0.21Tw0w0w0w0 """ import os import stat from datetime import datetime import aspen KB = 1024 MB = KB * 1024 GB = MB * 1024 TB = GB * 1024 PB = TB * 1024 EB = PB * 1024 def _get_size(stats): """Given a stat struct, return a size string. """ size = float(stats[stat.ST_SIZE]) if size < KB: return '%d    B' % (size) elif size < MB: return '%.1f kB' % (size / KB) elif size < GB: return '%.1f MB' % (size / MB) elif size < TB: return '%.1f GB' % (size / GB) elif size < PB: return '%.1f TB' % (size / TB) # :^) elif size < EB: return '%.1f PB' % (size / PB) # :^D else: return '%.1f EB' % (size / EB) # 8^D def _get_time(stats): """Given a stat struct, return a date stamp string. """ return str(datetime.fromtimestamp(stats[stat.ST_MTIME])) # Get the directory to list. # ========================== # Support the case where we are in the directory where this file actually # lives! fspath = request.headers.get('X-Aspen-AutoIndexDir', os.path.dirname(__file__)) assert os.path.isdir(fspath) # sanity check urlpath = fspath[len(request.website.www_root):] + os.sep urlpath = '/'.join(urlpath.split(os.sep)) title = urlpath and urlpath or '/' # Gather dirs, files, and others under this directory. # ==================================================== # We have to loop here and again below in order to guarantee sorted output. dirs = [] files = [] others = [] for name in os.listdir(fspath): if name.startswith('.'): # hidden files continue _fspath = os.path.join(fspath, name) if os.path.isdir(_fspath): el = dirs elif os.path.isfile(_fspath): el = files else: el = others _urlpath = urlpath + name stats = os.stat(_fspath) x = (stats, _fspath, _urlpath, name) el.append(x) dirs.sort() files.sort() others.sort() {{ title }}

{{ title }}

{% if fspath != request.website.www_root %} {% end %} {% for el in (dirs, files, others) %} {% for stats, _fspath, _urlpath, name in el %} {% if os.path.isdir(_fspath) %} {% elif os.path.isfile(_fspath) %} {% else %} {% end %} {% end %} {% end %}
Name Size Last Modified
../    
{{ name }}/  {{ name }} {{ _get_size(stats) }}{{ name }}  {{ _get_time(stats) }}