Skip to content

Instantly share code, notes, and snippets.

@kstep
Created May 10, 2011 16:21
Show Gist options
  • Save kstep/964803 to your computer and use it in GitHub Desktop.
Save kstep/964803 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# encoding: utf-8
import sys, os, itertools as it
try:
root = sys.argv[1]
except IndexError:
root = os.getcwd()
root = os.path.abspath(root)
print '''
<html>
<head>
<title>Directory tree from «%s»</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
/* !!! Please don't touch these rules !!! */
li.dir > ul {
display: none !important;
}
li.dir.opened > ul {
display: block !important;
}
/* Your styles here */
body {
font-family: sans-serif;
font-size: 11pt;
}
ul {
margin: 0pt 0pt 0pt 0.5em;
}
li {
margin: 0pt;
padding: 0pt;
}
li.dir {
list-style-image: url(file:///usr/share/icons/gnome/22x22/places/inode-directory.png);
}
li.file {
list-style-image: url(file:///usr/share/icons/gnome/22x22/mimetypes/gtk-file.png);
}
</style>
</head>
<body>
<ul>
''' % (root)
def builder(root):
return it.starmap(
lambda isdir, path, name:
'''<li class="dir"><a href="#%(path)s" name="%(path)s">%(name)s</a><ul>
%(content)s</ul></li>''' % dict(path=path, name=name, content=''.join(builder(path)))
if isdir
else '<li class="file">%s</li>' % name,
# remove sorted to get native order, add "key" argument to sorted() to define custom sorting
sorted(
# retrieve additional info (costly stat() calls)
it.imap(lambda names: (os.path.isdir(names[0]),) + names,
# full file name
it.imap(lambda name: (os.path.join(root, name), name),
# edit or remove this filter to get only desired files (e.g. name.endswith('.mp3'))
it.ifilter(
lambda name: not name.startswith('.'),
os.listdir(root)
))), key=lambda triple: (not triple[0], triple[2])))
for item in builder(root):
print item
print '''
</ul>
<script type="text/javascript">
var items = document.getElementsByClassName('dir');
var dochash = document.location.hash;
// Optimized for Firefox^W normal browsers,
// needs fixes to work under that fucking^W^W IE.
for (var i = 0, l = items.length; i < l; i++) {
(function (item) {
var link = item.firstChild;
if (link.hash == dochash) {
for (var n = item; n; n = n.parentNode)
n.tagName == 'LI' && n.classList && n.classList.add('opened');
}
link.addEventListener('click',
function (ev) {
item.classList.toggle('opened');
ev.preventDefault();
return false;
}, false);
})(items[i]);
}
</script>
</body>
</html>
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment