graph

package
v1.11.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package graph provides dependency graph analysis and visualization for proto files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RenderAnalysis

func RenderAnalysis(w io.Writer, result *AnalysisResult) error

RenderAnalysis renders analysis results.

Types

type AnalysisResult

type AnalysisResult struct {
	// Cycles are detected cycles in the graph.
	Cycles []CycleInfo
	// Orphans are nodes with no incoming or outgoing edges.
	Orphans []string
	// HeavyNodes are nodes with many transitive dependencies.
	HeavyNodes []HeavyNode
	// Coupling contains coupling metrics for each node.
	Coupling []CouplingMetrics
	// Layers suggests a layered architecture based on dependencies.
	Layers []Layer
}

AnalysisResult contains the results of graph analysis.

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer performs various analyses on graphs.

func NewAnalyzer

func NewAnalyzer(graph *Graph) *Analyzer

NewAnalyzer creates a new graph analyzer.

func (*Analyzer) Analyze

func (a *Analyzer) Analyze() *AnalysisResult

Analyze performs comprehensive analysis on the graph.

func (*Analyzer) CalculateCoupling

func (a *Analyzer) CalculateCoupling() []CouplingMetrics

CalculateCoupling calculates coupling metrics for all nodes.

func (*Analyzer) DetectCycles

func (a *Analyzer) DetectCycles() []CycleInfo

DetectCycles finds all cycles in the graph using DFS.

func (*Analyzer) FindHeavyNodes

func (a *Analyzer) FindHeavyNodes(limit int) []HeavyNode

FindHeavyNodes finds nodes with the most transitive dependencies.

func (*Analyzer) FindOrphans

func (a *Analyzer) FindOrphans() []string

FindOrphans finds nodes with no connections.

func (*Analyzer) FindUnusedFiles

func (a *Analyzer) FindUnusedFiles() []string

FindUnusedFiles finds files that are not imported by anyone (potential orphans).

func (*Analyzer) HasCycles

func (a *Analyzer) HasCycles() bool

HasCycles returns true if the graph has cycles.

func (*Analyzer) SuggestLayers

func (a *Analyzer) SuggestLayers() []Layer

SuggestLayers suggests a layered architecture based on dependency depth.

func (*Analyzer) ValidateAcyclic

func (a *Analyzer) ValidateAcyclic() error

ValidateAcyclic validates that the graph has no cycles.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder builds graphs from proto files.

func NewBuilder

func NewBuilder(log builder.Logger) *Builder

NewBuilder creates a new graph builder.

func (*Builder) BuildFromDependencyGraph

func (b *Builder) BuildFromDependencyGraph(depGraph *builder.DependencyGraph, scope Scope) (*Graph, error)

BuildFromDependencyGraph creates an enhanced graph from a DependencyGraph.

type CouplingMetrics

type CouplingMetrics struct {
	// NodeID is the analyzed node.
	NodeID string
	// AfferentCoupling (Ca) - number of nodes that depend on this node.
	AfferentCoupling int
	// EfferentCoupling (Ce) - number of nodes this node depends on.
	EfferentCoupling int
	// Instability = Ce / (Ca + Ce), ranges from 0 (stable) to 1 (unstable).
	Instability float64
}

CouplingMetrics contains coupling analysis results.

type CycleInfo

type CycleInfo struct {
	// Nodes are the node IDs forming the cycle.
	Nodes []string
	// Type is the type of nodes in the cycle.
	Type NodeType
}

CycleInfo contains information about a detected cycle.

type DOTRenderer

type DOTRenderer struct {
	// Title is the graph title.
	Title string
	// RankDir is the direction (TB, LR, BT, RL).
	RankDir string
}

DOTRenderer renders graphs in Graphviz DOT format.

func (*DOTRenderer) Render

func (r *DOTRenderer) Render(w io.Writer, graph *Graph) error

type Edge

type Edge struct {
	// From is the source node ID.
	From string
	// To is the target node ID.
	To string
	// Type describes the relationship.
	Type string
	// Weight is optional edge weight (for analysis).
	Weight int
}

Edge represents a directed edge in the graph.

type Format

type Format string

Format represents the output format for rendering.

const (
	FormatTree     Format = "tree"
	FormatDOT      Format = "dot"
	FormatMermaid  Format = "mermaid"
	FormatJSON     Format = "json"
	FormatPlantUML Format = "plantuml"
)

type Graph

type Graph struct {
	// Nodes are all nodes in the graph.
	Nodes map[string]*Node
	// Edges are all directed edges.
	Edges []*Edge
	// NodesByType indexes nodes by type.
	NodesByType map[NodeType][]*Node
	// AdjacencyList maps node ID to outgoing edges.
	AdjacencyList map[string][]*Edge
	// ReverseAdjacency maps node ID to incoming edges.
	ReverseAdjacency map[string][]*Edge
}

Graph represents an enhanced dependency graph with metadata.

func NewGraph

func NewGraph() *Graph

NewGraph creates a new empty graph.

func (*Graph) AddEdge

func (g *Graph) AddEdge(edge *Edge)

AddEdge adds an edge to the graph.

func (*Graph) AddNode

func (g *Graph) AddNode(node *Node)

AddNode adds a node to the graph.

func (*Graph) FilterByType

func (g *Graph) FilterByType(nodeType NodeType) *Graph

FilterByType returns a subgraph containing only nodes of the specified type.

func (*Graph) GetDependencies

func (g *Graph) GetDependencies(nodeID string) []string

GetDependencies returns node IDs that the given node depends on.

func (*Graph) GetDependents

func (g *Graph) GetDependents(nodeID string) []string

GetDependents returns node IDs that depend on the given node.

func (*Graph) GetIncomingEdges

func (g *Graph) GetIncomingEdges(nodeID string) []*Edge

GetIncomingEdges returns edges pointing to a node.

func (*Graph) GetNode

func (g *Graph) GetNode(id string) *Node

GetNode returns a node by ID.

func (*Graph) GetOutgoingEdges

func (g *Graph) GetOutgoingEdges(nodeID string) []*Edge

GetOutgoingEdges returns edges originating from a node.

func (*Graph) GetTransitiveDependencies

func (g *Graph) GetTransitiveDependencies(nodeID string) []string

GetTransitiveDependencies returns all transitive dependencies.

func (*Graph) GetTransitiveDependents

func (g *Graph) GetTransitiveDependents(nodeID string) []string

GetTransitiveDependents returns all nodes that transitively depend on this node.

func (*Graph) SortedNodes

func (g *Graph) SortedNodes() []*Node

SortedNodes returns nodes sorted by ID.

type HeavyNode

type HeavyNode struct {
	NodeID                 string
	TransitiveDependencies int
	TransitiveDependents   int
}

HeavyNode represents a node with many dependencies.

type JSONEdge

type JSONEdge struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Type   string `json:"type"`
	Weight int    `json:"weight,omitempty"`
}

JSONEdge is the JSON representation of an edge.

type JSONGraph

type JSONGraph struct {
	Nodes []JSONNode `json:"nodes"`
	Edges []JSONEdge `json:"edges"`
	Stats JSONStats  `json:"stats"`
}

JSONGraph is the JSON representation of a graph.

type JSONNode

type JSONNode struct {
	ID       string                 `json:"id"`
	Type     string                 `json:"type"`
	Name     string                 `json:"name"`
	Package  string                 `json:"package,omitempty"`
	FilePath string                 `json:"file_path,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

JSONNode is the JSON representation of a node.

type JSONRenderer

type JSONRenderer struct {
	// Indent enables pretty printing.
	Indent bool
}

JSONRenderer renders graphs as JSON.

func (*JSONRenderer) Render

func (r *JSONRenderer) Render(w io.Writer, graph *Graph) error

type JSONStats

type JSONStats struct {
	TotalNodes  int            `json:"total_nodes"`
	TotalEdges  int            `json:"total_edges"`
	NodesByType map[string]int `json:"nodes_by_type"`
	MaxDepth    int            `json:"max_depth"`
	AvgFanOut   float64        `json:"avg_fan_out"`
}

JSONStats contains graph statistics.

type Layer

type Layer struct {
	// Name is the layer name (e.g., "domain", "api", "infra").
	Name string
	// Level is the layer level (0 = lowest/foundation).
	Level int
	// Nodes are the node IDs in this layer.
	Nodes []string
}

Layer represents a suggested layer in the architecture.

type MermaidRenderer

type MermaidRenderer struct {
	// Direction is the graph direction (TD, LR, BT, RL).
	Direction string
}

MermaidRenderer renders graphs in Mermaid format.

func (*MermaidRenderer) Render

func (r *MermaidRenderer) Render(w io.Writer, graph *Graph) error

type Node

type Node struct {
	// ID is the unique identifier for the node.
	ID string
	// Type is the type of node.
	Type NodeType
	// Name is the display name.
	Name string
	// Package is the proto package name (for file nodes).
	Package string
	// FilePath is the file path (for non-file nodes, indicates source file).
	FilePath string
	// Metadata contains additional node information.
	Metadata map[string]interface{}
}

Node represents a node in the enhanced dependency graph.

type NodeMetric

type NodeMetric struct {
	NodeID string
	Value  int
}

TopNodes returns the top N nodes by a metric.

func GetTopByFanIn

func GetTopByFanIn(g *Graph, limit int) []NodeMetric

GetTopByFanIn returns nodes with the most incoming edges.

func GetTopByFanOut

func GetTopByFanOut(g *Graph, limit int) []NodeMetric

GetTopByFanOut returns nodes with the most outgoing edges.

func GetTopByTransitiveDeps

func GetTopByTransitiveDeps(g *Graph, limit int) []NodeMetric

GetTopByTransitiveDeps returns nodes with the most transitive dependencies.

type NodeType

type NodeType string

NodeType represents the type of a graph node.

const (
	NodeTypeFile    NodeType = "file"
	NodeTypePackage NodeType = "package"
	NodeTypeMessage NodeType = "message"
	NodeTypeService NodeType = "service"
	NodeTypeEnum    NodeType = "enum"
)

type PlantUMLRenderer

type PlantUMLRenderer struct{}

PlantUMLRenderer renders graphs in PlantUML format.

func (*PlantUMLRenderer) Render

func (r *PlantUMLRenderer) Render(w io.Writer, graph *Graph) error

type Renderer

type Renderer interface {
	Render(w io.Writer, graph *Graph) error
}

Renderer renders graphs to various formats.

func NewRenderer

func NewRenderer(format Format) Renderer

NewRenderer creates a renderer for the specified format.

type Scope

type Scope string

Scope defines the level of graph analysis.

const (
	// ScopeFile shows dependencies between files.
	ScopeFile Scope = "file"
	// ScopePackage shows dependencies between packages.
	ScopePackage Scope = "package"
	// ScopeMessage shows relationships between messages.
	ScopeMessage Scope = "message"
	// ScopeService shows service to message mappings.
	ScopeService Scope = "service"
	// ScopeFull shows all relationships.
	ScopeFull Scope = "full"
)

type Stats

type Stats struct {
	// TotalNodes is the total number of nodes.
	TotalNodes int
	// TotalEdges is the total number of edges.
	TotalEdges int
	// NodesByType counts nodes by type.
	NodesByType map[NodeType]int
	// FileCount is the number of file nodes.
	FileCount int
	// PackageCount is the number of unique packages.
	PackageCount int
	// MessageCount is the number of message nodes.
	MessageCount int
	// ServiceCount is the number of service nodes.
	ServiceCount int
	// EnumCount is the number of enum nodes.
	EnumCount int
	// MaxDepth is the maximum dependency depth.
	MaxDepth int
	// AvgDepth is the average dependency depth.
	AvgDepth float64
	// MaxFanOut is the maximum number of outgoing edges.
	MaxFanOut int
	// AvgFanOut is the average number of outgoing edges.
	AvgFanOut float64
	// MaxFanIn is the maximum number of incoming edges.
	MaxFanIn int
	// AvgFanIn is the average number of incoming edges.
	AvgFanIn float64
	// Density is the graph density (edges / possible edges).
	Density float64
	// ConnectedComponents is the number of connected components.
	ConnectedComponents int
}

Stats contains graph statistics.

func CalculateStats

func CalculateStats(g *Graph) Stats

CalculateStats calculates comprehensive statistics for a graph.

type TreeRenderer

type TreeRenderer struct{}

TreeRenderer renders graphs as ASCII trees.

func (*TreeRenderer) Render

func (r *TreeRenderer) Render(w io.Writer, graph *Graph) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL