Use the root attribute in codebase.visualize(G, root=root_symbol) to visualize trees

1

Prompt

Generate a directory tree for my project, showing all
directories and files up to 3 levels deep

You can adjust the depth and add specific conditions to refine your visualization.

2

Review

The assistant will provide a codemod using NetworkX to create the directory tree. Here’s an example of what the code might look like:

# Define the root folder for the directory tree
root_folder = "suma/apps/banking"

# Create a directed graph to represent the directory structure
G = nx.DiGraph()

for file in codebase.files:
    filepath = file.filepath
    if root_folder in filepath:
        parts = filepath.split("/")
        for i in range(len(parts)):
            path = "/".join(parts[: i + 1])
            
            if path != filepath:
                # Add directory nodes
                G.add_node(path, name=parts[i])
                if i > 0:
                    parent_path = "/".join(parts[:i])
                    G.add_edge(parent_path, path)
            else:
                # Add file nodes with usage information
                file = codebase.get_file(filepath)
                total_usages = sum(len(symbol.get_usages()) for symbol in file.symbols)
                G.add_node(path, name=parts[i], value=total_usages)
                if i > 0:
                    parent_path = "/".join(parts[:i])
                    G.add_edge(parent_path, path)

# Visualize the directory tree graph
codebase.visualize(G, root=root_folder)
3

Interact

Hit Run and view the graph in the Output Tab. For more advanced customization options, check out our customize page.