Skip to content

andy-c-jones/StructuraLens

Repository files navigation

StructuraLens

A high-performance .NET 10 CLI tool for analyzing C# codebases. StructuraLens provides comprehensive code complexity metrics, coupling analysis, and compiler diagnostics with multiple output formats optimized for different use cases.

Features

  • Code Complexity Metrics: Cyclomatic Complexity, Halstead Volume, Lines of Executable Code, Depth of Inheritance, and Maintainability Index calculated at method, type, and project levels
  • Coupling Analysis: Tracks dependencies between projects, namespaces, and types with internal/external split and dependency ratio metrics
  • Multiple Output Formats: JSON (machine-readable), HTML (interactive reports), Compact (99% smaller), and Summary (console-friendly)
  • Memory-Efficient: Adaptive aggregation strategies automatically handle large codebases with hundreds of projects
  • Compiler Diagnostics: Collects and reports all Roslyn compiler diagnostics with severity levels
  • Self-Contained Analysis: Uses Roslyn and MSBuild to analyze solutions without requiring compilation

Quick Start

Prerequisites

  • .NET 10 SDK
  • Node.js 18+ and npm

Installation

Download the latest release from the Releases page or build from source:

git clone https://github.com/andy-c-jones/StructuraLens.git
cd structuralens
dotnet build -c Release

Basic Usage

Analyze a solution and generate an HTML report:

structuralens analyze MySolution.sln --format html --out report.html

Diffing Reports (CI/PR)

Compare a base report to a head report and generate a diff:

structuralens diff --base base.json --head head.json --format json --out diff.json

Generate an HTML report with visual diff overlays:

structuralens diff --base base.json --head head.json --format html --out diff.html

Generate a Markdown summary for PR comments:

structuralens diff --base base.json --head head.json --format markdown --out diff.md

Analyze with JSON output (default):

structuralens analyze MySolution.sln --out report.json

Quick console summary:

structuralens analyze MySolution.sln --format summary

Generate compact format for large solutions:

structuralens analyze MySolution.sln --format compact --out report.slr

CLI Reference

analyze Command

Analyzes a C# solution or project and generates metrics reports.

Syntax:

structuralens analyze <path> [options]

Arguments:

  • <path> - Path to solution (.sln, .slnx) or project (.csproj) file

Options:

Option Short Description Default
--out -o Output file path for the report stdout
--format -f Output format: json, compact, html, summary json
--verbose -v Enable verbose logging (Debug level) false
--aggregation-strategy Memory strategy: InMemory, SQLite, Adaptive Adaptive
--memory-threshold Memory threshold in MB for adaptive strategy 1024
--sqlite-batch-size Batch size for SQLite operations 1000

Output Formats

  • json - Complete structured data, suitable for tooling integration
  • html - Interactive single-file HTML report with dependency graphs and filterable tables
  • compact - Optimized for size (~99% smaller), includes graph data for visualization
  • summary - Human-readable console output with key metrics and top complexity items

diff Command

Compares two JSON analysis reports and produces a diff summary.

Syntax:

structuralens diff --base <base.json> --head <head.json> [options]

Options:

Option Description Default
--format Output format: json, html, summary, markdown json
--out Output file path stdout
--max-projects Max projects in markdown table 10

See Usage Guide for detailed documentation.

Metrics Explained

Code Complexity

Metric Description Interpretation
Cyclomatic Complexity (CC) Number of independent paths CC > 10 suggests refactoring
Lines of Executable Code (LOC) Count of executable statements Higher LOC = more maintenance effort
Halstead Volume (V) Program size (operators + operands) Higher volume = more complex
Depth of Inheritance (DIT) Inheritance hierarchy depth Deep hierarchies can be fragile
Maintainability Index (MI) Overall maintainability (0-100) MI < 40 is difficult to maintain

Coupling Metrics

Metric Description Interpretation
Internal Dependencies (ID) Number of internal entities this entity depends on High ID = broader internal coupling surface
Internal Dependents (IDX) Number of internal entities that depend on this High IDX = heavily reused / high change impact
Dependency Ratio (DR) ID / (ID + IDX) 0.0 = provider-oriented, 1.0 = consumer-oriented
External Dependencies (ED) External namespaces/packages referenced Tracked separately from internal coupling

StructuraLens also reports external dependency breakdown:

  • EDB: External BCL dependencies (System.*, Microsoft.*)
  • EDP: External package dependencies (third-party)

Memory-Efficient Analysis

StructuraLens uses adaptive aggregation strategies to handle large codebases efficiently:

  • InMemory - Fast, best for small-medium solutions (up to ~50 projects)
  • SQLite - Disk-backed, best for large solutions (100+ projects), minimal memory usage
  • Adaptive (default) - Starts with InMemory, automatically migrates to SQLite when memory threshold exceeded

For large solutions, you can force SQLite mode:

structuralens analyze LargeSolution.sln --aggregation-strategy SQLite --verbose

Building from Source

Prerequisites

  • .NET 10 SDK
  • Node.js 18+ and npm (for HTML report template)
  • Git

Build Steps

git clone https://github.com/andy-c-jones/StructuraLens.git
cd structuralens
dotnet restore
dotnet build -c Release

The .NET build automatically runs npm install and npm run build in web/ to produce the HTML report template. To skip the web build (e.g. when iterating on C# code only):

dotnet build -p:SkipWebBuild=true

Run Tests

dotnet test

Run Locally

dotnet run --project src/StructuraLens.Cli -- analyze <path>

HTML Report Development

The interactive HTML report is built as an Astro project in web/. Astro compiles all CSS, TypeScript, and HTML into a single self-contained HTML file that is embedded into the .NET assembly as a resource at build time.

Architecture

  • Template: web/src/pages/index.astro — the single-page report layout
  • Styles: web/src/styles/ — theme, layout, components, and graph CSS
  • Scripts: web/src/scripts/ — TypeScript modules for tabs, tables, charts, D3 graph, etc.
  • Test data: web/src/test-data/ — golden JSON fixtures used during dev mode

In dev mode (astro dev), the template loads test data from web/src/test-data/. In production (astro build), it emits {{PLACEHOLDER}} tokens that the C# HtmlReportGenerator replaces with real analysis data at runtime.

Dev Server

Start the Astro dev server with hot-reload to iterate on the report UI:

cd web
npm install
npm run dev

This serves the report at http://localhost:4321 using the golden test data. Changes to .astro, .ts, and .css files are reflected instantly.

Production Build

Build the single-file HTML template:

cd web
npm run build

The output is written to web/dist/index.html and embedded into StructuraLens.Core.dll as a .NET resource on the next dotnet build.

Type Checking

Run the Astro TypeScript checker to validate all scripts:

cd web
npx astro check

Project Structure

StructuraLens/
├── src/
│   ├── StructuraLens.Core/      # Core analysis engine
│   └── StructuraLens.Cli/       # CLI application
├── tests/
│   └── StructuraLens.Tests/     # TUnit tests
├── web/                          # Astro project for HTML report template
│   ├── src/pages/index.astro    # Report template (single page)
│   ├── src/scripts/             # TypeScript modules (tabs, tables, D3 graph)
│   ├── src/styles/              # CSS (theme, layout, components, graph)
│   └── src/test-data/           # Golden JSON fixtures for dev mode
└── docs/                         # Documentation

Documentation

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch: feature/<short-description> or fix/<short-description>
  3. Make your changes with tests
  4. Use Conventional Commits for commit messages
  5. Open a pull request against main

Conventional Commit Examples:

  • feat: add new analysis rule for controller coupling
  • fix: handle null reference in parser when project file missing
  • chore: update dependencies
  • docs: clarify README examples

See Copilot Instructions for detailed contribution guidelines.

Exit Codes

Code Meaning
0 Success
1 Error (analysis failure, file not found, or unhandled exception)

License

Licensed under the MIT License (MIT).

See LICENSE.md for details.

Support

For issues, questions, or feature requests, please open an issue on GitHub.

About

C# codebase analysis tool

Topics

Resources

License

Stars

Watchers

Forks

Contributors