Last active
August 29, 2015 14:18
-
-
Save janpipek/fea41074555a35f9893a to your computer and use it in GitHub Desktop.
Quick HTML tree of file structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
import sys | |
from collections import OrderedDict | |
begin = u"""<!DOCTYPE html> | |
<html><head><meta charset="UTF-8"></head><style>li { | |
list-style: none; | |
} | |
li.dir:before { | |
content: "๐ "; | |
} | |
li.file:before { | |
content: "๐ "; | |
} | |
.error { | |
color: #f00; | |
} | |
</style><body>""" | |
end = """</body></html>""" | |
def generate_tree(path, depth=None, include_files=True, filter=None): | |
try: | |
files = sorted(os.listdir(path)) | |
dirs = [ f for f in files if os.path.isdir(os.path.join(path, f))] | |
if include_files: | |
regular_files = [ f for f in files if os.path.isfile(os.path.join(path, f))] | |
else: | |
regular_files = [ ] | |
if depth is not None: | |
if depth < 0: | |
regular_files = [] | |
dirs = [] | |
depth -= 1 | |
return { | |
"files" : [ f.decode("utf-8") for f in regular_files], | |
"dirs" : OrderedDict(((n.decode("utf-8"), generate_tree(os.path.join(path, n), depth=depth, include_files=include_files)) for n in dirs)), | |
"error" : False | |
} | |
except: | |
return { | |
"files" : [], | |
"dirs" : {}, | |
"error" : True | |
} | |
class Html(object): | |
"""Enable inclusion in ipython notebook""" | |
def __init__(self, t): | |
self.text = t | |
def _repr_html_(self): | |
return self.text | |
def __html__(self): | |
""" | |
This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
htmltag, etc) that this object is HTML and does not need things like | |
special characters (<>&) escaped. | |
""" | |
return self._repr_html_() | |
def __str__(self): | |
return self.text | |
def render_html(tree, toplevel=True, outfile=None): | |
if toplevel: | |
s = begin | |
else: | |
s = u"" | |
s += u"<ul>" | |
for name, subtree in tree["dirs"].items(): | |
if tree["error"]: | |
s += u"<li class='dir error'>" + name + "</li>" | |
else: | |
s += u"<li class='dir'>" + name | |
s += unicode(render_html(subtree, False)) | |
s += u"</li>" | |
for name in tree["files"]: | |
s += u"<li class='file'>%s</li>" % name | |
s += "</ul>" | |
if toplevel: | |
s += end | |
if outfile: | |
with open(outfile, "w") as f: | |
f.write(s) | |
return Html(s) | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
path = sys.argv[1] | |
else: | |
path = "." | |
tree = generate_tree(path) | |
print(render_html(tree)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately shows correct icons only in firefox