Last active
February 17, 2024 11:38
-
-
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/]
This file contains hidden or 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
#!/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