Skip to content

Instantly share code, notes, and snippets.

@steinfletcher
Last active February 17, 2024 11:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steinfletcher/323d97a016bd3eb126a3 to your computer and use it in GitHub Desktop.
Save steinfletcher/323d97a016bd3eb126a3 to your computer and use it in GitHub Desktop.
file system crawler to generate object tree json data for jsTree [http://www.jstree.com/]
#!/usr/bin/env python
import os
import json
class Node:
def __init__(self, id, text, parent):
self.id = id
self.text = text
self.parent = parent
def is_equal(self, node):
return self.id == node.id
def as_json(self):
return dict(
id=self.id,
parent=self.parent,
text=self.text
)
def get_nodes_from_path(path):
nodes = []
path_nodes = path.split("/")
for idx, node_name in enumerate(path_nodes):
parent = None
node_id = "/".join(path_nodes[0:idx+1])
if idx != 0:
parent = "/".join(path_nodes[0:idx])
else:
parent = "#"
nodes.append(Node(node_id, node_name, parent))
return nodes
def main():
unique_nodes = []
for root, dirs, files in os.walk(".", topdown=True):
for name in files:
path = os.path.join(root, name)
nodes = get_nodes_from_path(path)
for node in nodes:
if not any(node.is_equal(unode) for unode in unique_nodes):
unique_nodes.append(node)
print json.dumps([node.as_json() for node in unique_nodes])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment