graph

package
v0.0.0-...-460d0d3 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnableVerboseLogging

func EnableVerboseLogging()

EnableVerboseLogging enables verbose logging mode.

func Fmt

func Fmt(format string, args ...any)

Fmt prints formatted output if verbose logging is enabled.

func FormatType

func FormatType(v any) string

FormatType formats various types to string representation.

func GenerateMethodID

func GenerateMethodID(methodName string, parameters []string, sourceFile string, lineNumber ...uint32) string

GenerateMethodID generates a unique SHA256 hash ID for a method.

func GenerateSha256

func GenerateSha256(input string) string

GenerateSha256 generates a SHA256 hash from an input string.

func GetComposeServiceProperty

func GetComposeServiceProperty(node *Node, property string) string

GetComposeServiceProperty gets a property value from a compose service node.

func GetDockerInstructionType

func GetDockerInstructionType(node *Node) string

GetDockerInstructionType returns the instruction type for Docker nodes (e.g., "RUN", "FROM").

func HasComposeServiceProperty

func HasComposeServiceProperty(node *Node, property string, expectedValue ...string) bool

HasComposeServiceProperty checks if a compose service has a specific property.

func HasDockerInstructionArg

func HasDockerInstructionArg(node *Node, arg string) bool

HasDockerInstructionArg checks if a Docker node has a specific argument.

func IsComposeNode

func IsComposeNode(node *Node) bool

IsComposeNode checks if a node represents a docker-compose service.

func IsDockerNode

func IsDockerNode(node *Node) bool

IsDockerNode checks if a node represents a Dockerfile instruction.

func IsGitHubActions

func IsGitHubActions() bool

IsGitHubActions checks if running in GitHub Actions environment.

func Log

func Log(message string, args ...any)

Log logs a message if verbose logging is enabled.

func ResolveTransitiveInheritance

func ResolveTransitiveInheritance(codeGraph *CodeGraph)

ResolveTransitiveInheritance resolves transitive inheritance for Python classes. This fixes the issue where classes inheriting from custom enum/interface/dataclass base classes are not properly detected.

Example:

class CustomEnum(Enum):  # Detected as enum (direct inheritance)
    pass

class Operator(CustomEnum):  # NOT detected without this fix (transitive)
    pass

After this function, Operator will also be marked as "enum".

func SupportedLanguages

func SupportedLanguages() []string

SupportedLanguages returns a copy of the supported-language display names for use in user-facing messages.

Types

type CodeGraph

type CodeGraph struct {
	Nodes map[string]*Node
	Edges []*Edge
	// ProjectStats summarises what the file walk saw. Set by Initialize.
	// Callers read it to render meaningful empty-state messages when
	// len(Nodes) == 0 (e.g. "Detected: TypeScript (32), JavaScript (8)").
	ProjectStats ProjectStats
}

CodeGraph represents the entire code graph with nodes and edges.

func Initialize

func Initialize(directory string, callbacks *ProgressCallbacks) *CodeGraph

Initialize initializes the code graph by parsing all source files in a directory. If callbacks are provided, they will be called to report progress.

func NewCodeGraph

func NewCodeGraph() *CodeGraph

NewCodeGraph creates and initializes a new CodeGraph instance.

func (*CodeGraph) AddEdge

func (g *CodeGraph) AddEdge(from, to *Node)

AddEdge adds an edge between two nodes in the code graph.

func (*CodeGraph) AddNode

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

AddNode adds a node to the code graph.

func (*CodeGraph) FindNodesByType

func (g *CodeGraph) FindNodesByType(nodeType string) []*Node

FindNodesByType finds all nodes of a given type.

type ComposeGraph

type ComposeGraph struct {
	// Embedded YAML graph
	YAMLGraph *YAMLGraph

	// Compose-specific indexes
	Services map[string]*YAMLNode
	Volumes  map[string]*YAMLNode
	Networks map[string]*YAMLNode

	// Metadata
	Version  string
	FilePath string
}

ComposeGraph wraps a YAMLGraph with docker-compose specific indexing.

func NewComposeGraph

func NewComposeGraph(yamlGraph *YAMLGraph, filePath string) *ComposeGraph

NewComposeGraph creates a ComposeGraph from a YAMLGraph.

func ParseDockerCompose

func ParseDockerCompose(filePath string) (*ComposeGraph, error)

ParseDockerCompose parses a docker-compose.yml file.

func (*ComposeGraph) GetPrivilegedServices

func (c *ComposeGraph) GetPrivilegedServices() []string

GetPrivilegedServices returns services with privileged: true.

func (*ComposeGraph) GetServices

func (c *ComposeGraph) GetServices() []string

GetServices returns all service names.

func (*ComposeGraph) ServiceExposesPort

func (c *ComposeGraph) ServiceExposesPort(serviceName string, port int) bool

ServiceExposesPort checks if a service exposes a specific port.

func (*ComposeGraph) ServiceGet

func (c *ComposeGraph) ServiceGet(serviceName, key string) any

ServiceGet retrieves a service property value.

func (*ComposeGraph) ServiceGetLineNumber

func (c *ComposeGraph) ServiceGetLineNumber(serviceName, key string) int

ServiceGetLineNumber retrieves the line number for a service property. Returns the line number of the property's value, or the service line if property doesn't exist.

func (*ComposeGraph) ServiceHas

func (c *ComposeGraph) ServiceHas(serviceName, key string, value any) bool

ServiceHas checks if a service has a property with specified value.

func (*ComposeGraph) ServiceHasCapability

func (c *ComposeGraph) ServiceHasCapability(serviceName, capability, capType string) bool

ServiceHasCapability checks for capability in cap_add or cap_drop.

func (*ComposeGraph) ServiceHasEnvVar

func (c *ComposeGraph) ServiceHasEnvVar(serviceName, varName string) bool

ServiceHasEnvVar checks if service has environment variable.

func (*ComposeGraph) ServiceHasKey

func (c *ComposeGraph) ServiceHasKey(serviceName, key string) bool

ServiceHasKey checks if a service has a property defined.

func (*ComposeGraph) ServiceHasSecurityOpt

func (c *ComposeGraph) ServiceHasSecurityOpt(serviceName, optValue string) bool

ServiceHasSecurityOpt checks for specific security_opt value.

func (*ComposeGraph) ServicesWithDockerSocket

func (c *ComposeGraph) ServicesWithDockerSocket() []string

ServicesWithDockerSocket returns services that mount Docker socket.

func (*ComposeGraph) ServicesWithHostNetwork

func (c *ComposeGraph) ServicesWithHostNetwork() []string

ServicesWithHostNetwork returns services using network_mode: host.

func (*ComposeGraph) ServicesWithoutReadOnly

func (c *ComposeGraph) ServicesWithoutReadOnly() []string

ServicesWithoutReadOnly returns services without read_only: true.

type Edge

type Edge struct {
	From *Node
	To   *Node
}

Edge represents a directed edge between two nodes in the code graph.

type Node

type Node struct {
	ID                   string
	Type                 string
	Name                 string
	CodeSnippet          string // DEPRECATED: Will be removed, use GetCodeSnippet() instead
	SourceLocation       *SourceLocation
	LineNumber           uint32
	OutgoingEdges        []*Edge
	IsExternal           bool
	Modifier             string
	ReturnType           string
	MethodArgumentsType  []string
	MethodArgumentsValue []string
	PackageName          string
	ImportPackage        []string
	SuperClass           string
	Interface            []string
	DataType             string
	Scope                string
	VariableValue        string
	File                 string

	ThrowsExceptions  []string
	Annotation        []string
	JavaDoc           *model.Javadoc
	BinaryExpr        *model.BinaryExpr
	ClassInstanceExpr *model.ClassInstanceExpr
	IfStmt            *model.IfStmt
	WhileStmt         *model.WhileStmt
	DoStmt            *model.DoStmt
	ForStmt           *model.ForStmt
	BreakStmt         *model.BreakStmt
	ContinueStmt      *model.ContinueStmt
	YieldStmt         *model.YieldStmt
	AssertStmt        *model.AssertStmt
	ReturnStmt        *model.ReturnStmt
	BlockStmt         *model.BlockStmt
	Language          string         // "go", "python", "java" - set during parsing
	Metadata          map[string]any // Generic key-value store for language/tool-specific metadata
	// contains filtered or unexported fields
}

Node represents a node in the code graph with various properties describing code elements like classes, methods, variables, etc.

func (*Node) GetCodeSnippet

func (n *Node) GetCodeSnippet() string

GetCodeSnippet returns the code snippet for this node. If SourceLocation is set, it reads from the file (lazy loading). Otherwise, it returns the deprecated CodeSnippet field for backward compatibility.

type ProgressCallbacks

type ProgressCallbacks struct {
	// OnStart is called once before processing begins, with the total number of files.
	OnStart func(totalFiles int)
	// OnProgress is called after each file is processed (successfully or with error).
	OnProgress func()
	// ExcludePatterns holds validated, normalized repo-relative path prefixes.
	// A file is skipped during the walk if its repo-relative path starts with any prefix.
	// Use validateExcludePatterns in the cmd package to produce this slice.
	ExcludePatterns []string
}

ProgressCallbacks contains optional callbacks for tracking initialization progress.

type ProjectStats

type ProjectStats struct {
	// TotalFiles is the count of every regular file walked, after applying
	// the skip-directory list and --exclude patterns.
	TotalFiles int
	// ScannedFiles is the count of files routed to one of the supported
	// tree-sitter parsers. Equals len(files) returned from getFiles.
	ScannedFiles int
	// ByLanguage is a language-display-name → file-count map covering every
	// file walked, both supported and unsupported. Files in formats
	// pathfinder cannot classify (binaries, lock files, dotfiles) are
	// omitted entirely rather than bucketed as "Other"; this keeps the
	// downstream "Detected: …" line honest about what's actually source.
	ByLanguage map[string]int
}

ProjectStats summarises the file population that a single getFiles walk observed. It is exposed on CodeGraph so callers (cmd/scan, cmd/ci) can render a meaningful empty-state message when the graph ended up with zero parseable nodes, instead of exiting with a generic "no source files" error.

Counts only include files that survived the always-skipped directories (vendor, node_modules, .git, etc.) and the user's --exclude prefixes; the goal is files the user expected pathfinder to look at, not every regular file on disk.

func (ProjectStats) UnsupportedFileCount

func (s ProjectStats) UnsupportedFileCount() int

UnsupportedFileCount returns the total number of detected files whose language is not in the supported set. Used for the headline number in the "Scanned 0 of N files (M unsupported)" line.

func (ProjectStats) UnsupportedSummary

func (s ProjectStats) UnsupportedSummary(topN int) string

UnsupportedSummary returns the top-N unsupported languages formatted as "TypeScript (32), JavaScript (8), JSON (5), Markdown (2)". Returns "" if no unsupported files were detected. A topN of 0 or less means unbounded. Ties are broken by language name (alphabetical) for deterministic output.

type SourceLocation

type SourceLocation struct {
	File      string
	StartByte uint32
	EndByte   uint32
}

SourceLocation stores the file location of a code snippet for lazy loading.

type YAMLGraph

type YAMLGraph struct {
	Root     *YAMLNode
	FilePath string
}

YAMLGraph represents a parsed YAML document.

func ParseYAML

func ParseYAML(filePath string) (*YAMLGraph, error)

ParseYAML parses a YAML file and returns a YAMLGraph.

func ParseYAMLString

func ParseYAMLString(content string, filePath ...string) (*YAMLGraph, error)

ParseYAMLString parses a YAML string and returns a YAMLGraph.

func (*YAMLGraph) Query

func (yg *YAMLGraph) Query(key string) *YAMLNode

Query retrieves a top-level node by key.

type YAMLNode

type YAMLNode struct {
	Value      any
	Children   map[string]*YAMLNode
	Type       string // "scalar", "mapping", "sequence"
	LineNumber int    // Line number in source file (1-indexed)
}

YAMLNode represents a node in the YAML tree.

func (*YAMLNode) BoolValue

func (yn *YAMLNode) BoolValue() bool

BoolValue returns the value as a boolean.

func (*YAMLNode) GetChild

func (yn *YAMLNode) GetChild(key string) *YAMLNode

GetChild retrieves a child node by key.

func (*YAMLNode) HasChild

func (yn *YAMLNode) HasChild(key string) bool

HasChild checks if a node has a child with the given key.

func (*YAMLNode) ListValues

func (yn *YAMLNode) ListValues() []any

ListValues returns the value as a slice (for sequence nodes).

func (*YAMLNode) StringValue

func (yn *YAMLNode) StringValue() string

StringValue returns the value as a string.

Directories

Path Synopsis
Package callgraph provides static call graph analysis for Python code.
Package callgraph provides static call graph analysis for Python code.
analysis/taint
Package taint provides intra-procedural taint analysis for detecting data flow from sources to sinks.
Package taint provides intra-procedural taint analysis for detecting data flow from sources to sinks.
builder
Package builder provides call graph construction orchestration.
Package builder provides call graph construction orchestration.
cfg
Package cfg provides control flow graph (CFG) construction and analysis.
Package cfg provides control flow graph (CFG) construction and analysis.
core
Package core provides foundational type definitions for the callgraph analyzer.
Package core provides foundational type definitions for the callgraph analyzer.
extraction
Package extraction provides AST-based code extraction utilities for Python source code.
Package extraction provides AST-based code extraction utilities for Python source code.
patterns
Package patterns provides security and framework pattern detection.
Package patterns provides security and framework pattern detection.
registry
Package registry provides module, type, and attribute registry functionality for Python code analysis.
Package registry provides module, type, and attribute registry functionality for Python code analysis.
resolution
Package resolution provides bidirectional type inference.
Package resolution provides bidirectional type inference.
resolution/strategies
Package strategies provides AttributeAccessStrategy for general attribute access.
Package strategies provides AttributeAccessStrategy for general attribute access.
Package clike contains shared helpers for parsing C and C++ source files.
Package clike contains shared helpers for parsing C and C++ source files.

Jump to

Keyboard shortcuts

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