CodeGraph

repository·main·Indexed 19 days ago

https://github.com/xnuinside/codegraph

A static code analyzer for Python that generates interactive visual diagrams of code structures. It maps dependencies between modules, classes, and functions without executing the code. Version 1.2.0 supports D3.js interactive HTML visualizations, legacy matplotlib plots, and CSV data exports.

Tokens
5.7K
Snippets
24
Records
30
Agent score
66%

What's inside codegraph

  1. Extend CodeGraph with new visualizers or parsers

    main

    CodeGraph is designed with several extension points for developers looking to build on top of it:

    1. New Visualizers: Add new rendering logic or export formats (like JSON or DOT) by adding functions to codegraph/vizualyzer.py.
    2. New Parsers: Extend codegraph/parser.py to support languages other than Python.
    3. New Link Types: Update the convert_to_d3_format() function in vizualyzer.py to handle new relationship definitions.
  2. How CodeGraph works: Data Flow and Architecture

    main

    CodeGraph follows a linear pipeline to transform Python source code into an interactive dependency graph:

    1. Path Discovery: The CLI receives paths, and utils.get_python_paths_list() recursively finds all .py files.
    2. Parsing: parser.create_objects_array() parses each file to extract functions, classes, methods, and import statements.
    3. Graph Building: core.CodeGraph.usage_graph() maps entities to line ranges, identifies where they are used, and creates dependency edges.
    4. Visualization: vizualyzer.draw_graph() converts the graph into a D3.js format and generates an HTML file with embedded JavaScript, which is then opened in a browser.

    Core Data Flow Summary: Python Files $\rightarrow$ Parser $\rightarrow$ Code Objects $\rightarrow$ Import Analysis $\rightarrow$ Entity Usage $\rightarrow$ Dependency Graph

  3. Understand Node and Link types in CodeGraph visualizations

    main

    When viewing a CodeGraph visualization, nodes and links are categorized by type to represent the structure of your code:

    Node Types

    TypeVisualDescription
    ModuleGreen squareA Python .py file
    EntityBlue circleA function or class
    ExternalGray circleA dependency from outside the analyzed codebase
    TypeVisualDescription
    module-entityGreen dashedIndicates a module contains a specific entity
    module-moduleOrange solidIndicates one module imports from another module
    dependencyRedIndicates an entity uses another entity
  4. Navigate and interact with the CodeGraph visualization

    main

    The interactive HTML visualization provides several ways to explore your code structure:

    • Zoom & Pan: Use the mouse wheel to zoom and drag the background to pan.
    • Reposition Nodes: Drag individual nodes to move them within the graph.

    Search & Discovery

    • Search: Press Ctrl+F (or Cmd+F on Mac) to open the search bar with autocomplete. Results are color-coded by node type.
    • Highlighting: Click a node to highlight it and its direct connections; all other nodes will be dimmed.
    • Tooltips: Hover over a node to view its type, parent module, full file path, and connection count.

    Analysis Panels

    • Unlinked Modules: An 'Unlinked Panel' lists modules with no connections. Clicking a module navigates directly to it on the graph.
    • Massive Objects Detection: A 'Massive Objects Panel' helps find large entities (modules, classes, functions) based on lines of code. You can filter by type and set a custom threshold.

    Display Settings

    • Size Scaling: You can toggle node size scaling based on lines of code (larger nodes represent more code).
  5. Generate a code structure visualization

    main

    To analyze a Python project and generate an interactive HTML diagram of its structure (showing dependencies between modules, classes, and functions), run the codegraph command followed by the path to your code. This will automatically open the visualization in your default browser.

    codegraph /path/to/your_python_code
  6. Use the CodeGraph CLI to visualize code dependencies

    main

    CodeGraph is a static code analyzer that creates a graph of code entities (methods, classes, etc.) based on lex and syntax parsing without executing the code. You can use the CLI to generate interactive D3.js HTML visualizations, Matplotlib plots, or export graph data to CSV.

    Basic usage requires providing at least one path to a codebase:

    codegraph /path/to/your/code
    codegraph /path/to/your/code
  7. Export graph data to CSV

    main

    You can export the analyzed code structure to a CSV file for use in spreadsheets or other data analysis tools using the --csv flag.

    CSV Columns:

    • name: Entity name
    • type: Entity type (module, function, class, or external)
    • parent_module: The parent module (applicable to functions and classes)
    • full_path: The file path
    • links_out: Count of outgoing dependencies
    • links_in: Count of incoming dependencies
    • lines: Lines of code in the entity
    codegraph /path/to/code --csv output.csv
  8. CodeGraph CLI options reference

    main

    The codegraph CLI tool supports the following options:

    OptionDescription
    --output PATHCustom output path for the generated HTML file (default: ./codegraph.html)
    --matplotlibUse legacy matplotlib visualization instead of D3.js (requires codegraph[matplotlib])
    -o, --object-onlyPrint dependencies to the console only; no HTML visualization is generated
    | Option | Description |
    |-------|-------------|
    | `--output PATH` | Custom output path for the HTML file (default: `./codegraph.html`) |
    | `--matplotlib` | Use legacy matplotlib visualization instead of D3.js (requires `codegraph[matplotlib]`)
    | `-o, --object-only` | Print dependencies to console only, no visualization |
  9. Reference the D3.js Data Format

    main

    The visualizer converts the internal graph into a specific JSON format used by D3.js for rendering nodes and links. This format is useful if you intend to implement custom visualizers or export the data.

    Nodes Schema:

    • id: Unique identifier (e.g., module.py or module.py:func).
    • type: The type of node (module, entity).
    • label: (Optional) The name of the entity.
    • parent: (Optional) The ID of the parent module.
    • collapsed: (Optional) Boolean state for module expansion.

    Links Schema:

    • source: The ID of the starting node.
    • target: The ID of the ending node.
    • type: The relationship type (module-entity, module-module, dependency).
    {
      "nodes": [
        {"id": "module.py", "type": "module", "collapsed": false},
        {"id": "module.py:func", "label": "func", "type": "entity", "parent": "module.py"}
      ],
      "links": [
        {"source": "module.py", "target": "module.py:func", "type": "module-entity"},
        {"source": "module.py:func", "target": "other.py:dep", "type": "dependency"}
      ]
    }
  10. Use CodeGraph to visualize code structure

    main

    Run the codegraph command followed by the path to the Python code you wish to analyze. This generates an interactive HTML visualization and opens it in your default web browser.

    CodeGraph performs static analysis using lexical and syntax parsing, meaning it does not execute your code and does not require you to activate environments or install the target code's dependencies.

    codegraph /path/to/your_python_code