Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eliasdorneles/2d47f66d81dd706a2d0d0e76ee8e3382 to your computer and use it in GitHub Desktop.
Save eliasdorneles/2d47f66d81dd706a2d0d0e76ee8e3382 to your computer and use it in GitHub Desktop.
Script to filter the packages graph generated by pyreverse on depth
import argparse
import pydot
def should_delete(node_name, max_depth=2):
return node_name.count(".") >= max_depth
def truncate_node_name(node_name, max_depth=2):
return '.'.join(node_name.strip('"').split('.')[:max_depth])
def filter_and_delete_nodes(dot_file, output_file, max_depth=2):
# Load the .dot file
graph = pydot.graph_from_dot_file(dot_file)[0]
# Create a list to hold nodes and edges to remove
nodes_to_remove = []
edges_to_remove = []
edges_to_add = set()
for node in graph.get_nodes():
# Get the name of the node
node_name = node.get_name().strip('"')
if should_delete(node_name, max_depth):
nodes_to_remove.append(node)
# Find edges connected to the current node and mark for removal
for edge in graph.get_edges():
if should_delete(edge.get_source(), max_depth) or should_delete(edge.get_destination(), max_depth):
edges_to_remove.append(edge)
# Track parent nodes, we'll add these back later
edges_to_add.add((truncate_node_name(edge.get_source(), max_depth), truncate_node_name(edge.get_destination(), max_depth)))
# Remove the marked nodes and edges
for node in nodes_to_remove:
graph.del_node(node.get_name())
for edge in edges_to_remove:
graph.del_edge(edge.get_source(), edge.get_destination())
# Add edges between parents of removed nodes
for edge in edges_to_add:
graph.add_edge(pydot.Edge(edge[0], edge[1]))
# Save the modified graph to a new .dot file
graph.write_dot(output_file)
print(f"Modified graph saved to {output_file}")
def main(args):
filter_and_delete_nodes(args.dot_file, args.output, args.max_depth)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("dot_file", type=str, help="Path to the .dot file")
parser.add_argument("--output", type=str, default="modified_graph.dot", help="Path to the output file")
parser.add_argument("--max-depth", type=int, default=2, help="Maximum depth of the node")
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment