Documentation
¶
Overview ¶
Package analyze provides analyze functionality.
Index ¶
- Constants
- Variables
- func HistoryKeysByID(leaves map[string]HistoryAnalyzer, ids []string) ([]string, error)
- func NormalizeFormat(format string) string
- func OrderedRunIDs(registry *Registry, ids []string) ([]string, error)
- func OutputHistoryResults(leaves []HistoryAnalyzer, results map[HistoryAnalyzer]Report, format string, ...) error
- func PrintHeader(writer io.Writer)
- func RegisterPlotRenderer(fn PlotRenderer)
- func RegisterPlotSections(analyzerID string, fn SectionRendererFunc)
- func RegisterTickExtractor(analyzerFlag string, fn TickExtractor)
- func ReportFunctionList(report Report, key string) ([]map[string]any, bool)
- func ResolveFormats(format string, hasStatic, hasHistory bool) (staticFmt, historyFmt string, err error)
- func ResolveInputFormat(inputPath, inputFormat string) (string, error)
- func ShouldSkipFolderNode(path string, entry os.DirEntry, walkErr error, parser *uast.Parser) (bool, error)
- func UniversalFormats() []string
- func ValidateFormat(format string, supported []string) (string, error)
- func ValidateUniversalFormat(format string) (string, error)
- func WriteConvertedOutput(model UnifiedModel, outputFormat string, writer io.Writer) error
- func WriteMergedTimeSeries(ts *MergedTimeSeries, writer io.Writer) error
- type AnalysisVisitor
- type Analyzer
- type AnalyzerMode
- type AnalyzerResult
- type BaseReportSection
- func (b *BaseReportSection) AllIssues() []Issue
- func (b *BaseReportSection) Distribution() []DistributionItem
- func (b *BaseReportSection) KeyMetrics() []Metric
- func (b *BaseReportSection) Score() float64
- func (b *BaseReportSection) ScoreLabel() string
- func (b *BaseReportSection) SectionTitle() string
- func (b *BaseReportSection) StatusMessage() string
- func (b *BaseReportSection) TopIssues(_ int) []Issue
- type CommitIdentity
- type CommitLike
- type CommitMeta
- type CommitParents
- type Context
- type Descriptor
- type DistributionItem
- type Factory
- type HistoryAnalyzer
- type Issue
- type MergedCommitData
- type MergedTimeSeries
- type Metric
- type MultiAnalyzerTraverser
- type NodeVisitor
- type Parallelizable
- type PlotGenerator
- type PlotRenderer
- type PlumbingSnapshot
- type PreparationConfig
- type PreparedCommit
- type Registry
- func (r *Registry) All() []Descriptor
- func (r *Registry) Descriptor(id string) (Descriptor, bool)
- func (r *Registry) ExpandPatterns(patterns []string) ([]string, error)
- func (r *Registry) IDsByMode(mode AnalyzerMode) []string
- func (r *Registry) SelectedIDs(patterns []string) ([]string, error)
- func (r *Registry) Split(ids []string) (staticIDs, historyIDs []string, err error)
- type Report
- type ReportSection
- type ReportSectionProvider
- type ResultAggregator
- type SectionGenerator
- type SectionRendererFunc
- type StaticAnalyzer
- type StaticRenderer
- type StaticService
- func (svc *StaticService) AnalyzeFolder(ctx context.Context, rootPath string, analyzerList []string) (map[string]Report, error)
- func (svc *StaticService) AnalyzerNamesByID(ids []string) ([]string, error)
- func (svc *StaticService) BuildSections(results map[string]Report) []ReportSection
- func (svc *StaticService) FindAnalyzer(name string) StaticAnalyzer
- func (svc *StaticService) FormatCompact(results map[string]Report, noColor bool, writer io.Writer) error
- func (svc *StaticService) FormatJSON(results map[string]Report, writer io.Writer) error
- func (svc *StaticService) FormatPerAnalyzer(analyzerNames []string, results map[string]Report, format string, ...) error
- func (svc *StaticService) FormatText(results map[string]Report, verbose, noColor bool, writer io.Writer) error
- func (svc *StaticService) RunAndFormat(ctx context.Context, path string, analyzerIDs []string, format string, ...) error
- type Thresholds
- type TickExtractor
- type UnifiedModel
- func DecodeBinaryInputModel(input []byte, orderedIDs []string, registry *Registry) (UnifiedModel, error)
- func DecodeInputModel(input []byte, inputFormat string, orderedIDs []string, registry *Registry) (UnifiedModel, error)
- func NewUnifiedModel(results []AnalyzerResult) UnifiedModel
- func ParseUnifiedModelJSON(data []byte) (UnifiedModel, error)
- type VisitorProvider
Constants ¶
const ( // FormatBinAlias is a short CLI alias for binary output. FormatBinAlias = "bin" // FormatText is the human-readable static analysis output format. FormatText = "text" // FormatCompact is the single-line-per-analyzer static analysis output format. FormatCompact = "compact" // FormatTimeSeries is the unified time-series output format that merges // all history analyzer data into a single JSON array keyed by commit. FormatTimeSeries = "timeseries" )
const ( FormatYAML = "yaml" FormatJSON = "json" FormatBinary = "binary" FormatPlot = "plot" )
Serialization format constants.
const ( SeverityGood = "good" SeverityFair = "fair" SeverityPoor = "poor" SeverityInfo = "info" )
Severity constants for Issue classification.
const InputFormatAuto = "auto"
InputFormatAuto is the default input format that triggers extension-based detection.
const ScoreInfoOnly = -1.0
ScoreInfoOnly indicates a section has no score (info only).
const ScoreLabelInfo = "Info"
ScoreLabelInfo is the label shown for info-only sections.
const TimeSeriesModelVersion = "codefang.timeseries.v1"
TimeSeriesModelVersion is the schema version for unified time-series output.
const UnifiedModelVersion = "codefang.run.v1"
UnifiedModelVersion is the schema version for converted run outputs.
Variables ¶
var ( // ErrInvalidMixedFormat indicates a format that cannot be used in combined static+history runs. ErrInvalidMixedFormat = errors.New("invalid mixed format") // ErrInvalidStaticFormat indicates an invalid static analysis output format. ErrInvalidStaticFormat = errors.New("invalid static format") // ErrInvalidHistoryFormat indicates an invalid history analysis output format. ErrInvalidHistoryFormat = errors.New("invalid history format") // ErrInvalidInputFormat indicates an unrecognized input format. ErrInvalidInputFormat = errors.New("invalid input format") // ErrLegacyInputAmbiguous indicates legacy input requires exactly one analyzer. ErrLegacyInputAmbiguous = errors.New("legacy input requires exactly one analyzer id") // ErrLegacyBinaryCount indicates a binary envelope count mismatch. ErrLegacyBinaryCount = errors.New("legacy binary envelope count mismatch") )
var ErrAnalysisFailed = errors.New("analysis failed")
ErrAnalysisFailed indicates that one or more analyzers failed during parallel execution.
var ErrDuplicateAnalyzerID = errors.New("duplicate analyzer id")
ErrDuplicateAnalyzerID is returned when registry receives duplicate IDs.
var ErrInvalidAnalyzerGlob = errors.New("invalid analyzer glob")
ErrInvalidAnalyzerGlob is returned when a glob pattern is malformed.
var ErrInvalidAnalyzerMode = errors.New("invalid analyzer mode")
ErrInvalidAnalyzerMode is returned when analyzer mode mismatches runtime category.
var ErrInvalidUnifiedModel = errors.New("invalid unified model")
ErrInvalidUnifiedModel indicates malformed canonical conversion data.
var ErrNilRootNode = errors.New("root node is nil")
ErrNilRootNode indicates that a nil root node was passed to an analyzer.
var ErrRendererNotSet = errors.New("static service renderer not set")
ErrRendererNotSet is returned when a formatting method is called without a Renderer.
var ErrUnknownAnalyzerID = errors.New("unknown analyzer id")
ErrUnknownAnalyzerID is returned when registry lookup fails.
var ErrUnregisteredAnalyzer = errors.New("no registered analyzer with name")
ErrUnregisteredAnalyzer indicates that no analyzer with the given name is registered.
var ( // ErrUnsupportedFormat indicates the requested output format is not supported. ErrUnsupportedFormat = errors.New("unsupported format") )
Functions ¶
func HistoryKeysByID ¶
func HistoryKeysByID(leaves map[string]HistoryAnalyzer, ids []string) ([]string, error)
HistoryKeysByID maps history analyzer IDs to their pipeline keys.
func NormalizeFormat ¶
NormalizeFormat canonicalizes a user-provided output format string.
func OrderedRunIDs ¶
OrderedRunIDs splits the provided analyzer IDs by mode via the registry and returns them in static-first, history-second order.
func OutputHistoryResults ¶
func OutputHistoryResults( leaves []HistoryAnalyzer, results map[HistoryAnalyzer]Report, format string, writer io.Writer, ) error
OutputHistoryResults outputs the results for all selected history leaves.
func PrintHeader ¶
PrintHeader prints the codefang version header.
func RegisterPlotRenderer ¶
func RegisterPlotRenderer(fn PlotRenderer)
RegisterPlotRenderer sets the package-level plot renderer used by WriteConvertedOutput. It is intended to be called from the renderer package's init function.
func RegisterPlotSections ¶
func RegisterPlotSections(analyzerID string, fn SectionRendererFunc)
RegisterPlotSections registers a plot section renderer for the given analyzer ID.
func RegisterTickExtractor ¶
func RegisterTickExtractor(analyzerFlag string, fn TickExtractor)
RegisterTickExtractor registers a tick extractor for the given analyzer flag. Analyzers call this during initialization to opt into unified time-series output.
func ReportFunctionList ¶
ReportFunctionList extracts a []map[string]any from a report key. Handles both direct typed values and JSON-decoded []any slices.
func ResolveFormats ¶
func ResolveFormats(format string, hasStatic, hasHistory bool) (staticFmt, historyFmt string, err error)
ResolveFormats determines the output formats for static and history phases based on the user-provided format string and whether each phase is active.
func ResolveInputFormat ¶
ResolveInputFormat determines the input format from the provided path and explicit format hint. When the format is empty or InputFormatAuto, the extension of inputPath is used to detect the format.
func ShouldSkipFolderNode ¶
func ShouldSkipFolderNode(path string, entry os.DirEntry, walkErr error, parser *uast.Parser) (bool, error)
ShouldSkipFolderNode decides whether a folder walk entry should be skipped.
func UniversalFormats ¶
func UniversalFormats() []string
UniversalFormats returns the canonical output formats supported by all analyzers.
func ValidateFormat ¶
ValidateFormat checks whether a format is in the provided support list.
func ValidateUniversalFormat ¶
ValidateUniversalFormat checks whether a format belongs to the universal contract.
func WriteConvertedOutput ¶
func WriteConvertedOutput(model UnifiedModel, outputFormat string, writer io.Writer) error
WriteConvertedOutput encodes the unified model into the requested output format and writes it to the provided writer.
func WriteMergedTimeSeries ¶
func WriteMergedTimeSeries(ts *MergedTimeSeries, writer io.Writer) error
WriteMergedTimeSeries encodes a MergedTimeSeries as indented JSON to the writer.
Types ¶
type AnalysisVisitor ¶
type AnalysisVisitor interface {
NodeVisitor
GetReport() Report
}
AnalysisVisitor extends NodeVisitor to provide analysis results.
type Analyzer ¶
type Analyzer interface {
Name() string
Flag() string
Descriptor() Descriptor
// Configuration.
ListConfigurationOptions() []pipeline.ConfigurationOption
Configure(facts map[string]any) error
}
Analyzer is the common base interface for all analyzers.
type AnalyzerMode ¶
type AnalyzerMode string
AnalyzerMode identifies analyzer runtime mode.
const ( ModeStatic AnalyzerMode = "static" ModeHistory AnalyzerMode = "history" )
Analyzer modes.
type AnalyzerResult ¶
type AnalyzerResult struct {
ID string `json:"id" yaml:"id"`
Mode AnalyzerMode `json:"mode" yaml:"mode"`
Report Report `json:"report" yaml:"report"`
}
AnalyzerResult represents one analyzer report in canonical converted output.
type BaseReportSection ¶
BaseReportSection provides default implementations for ReportSection. Analyzers can embed this and override specific methods.
func (*BaseReportSection) AllIssues ¶
func (b *BaseReportSection) AllIssues() []Issue
AllIssues returns nil by default. Override to provide all issues.
func (*BaseReportSection) Distribution ¶
func (b *BaseReportSection) Distribution() []DistributionItem
Distribution returns nil by default. Override to provide distribution data.
func (*BaseReportSection) KeyMetrics ¶
func (b *BaseReportSection) KeyMetrics() []Metric
KeyMetrics returns nil by default. Override to provide metrics.
func (*BaseReportSection) Score ¶
func (b *BaseReportSection) Score() float64
Score returns the score value.
func (*BaseReportSection) ScoreLabel ¶
func (b *BaseReportSection) ScoreLabel() string
ScoreLabel returns formatted score or "Info" for info-only sections.
func (*BaseReportSection) SectionTitle ¶
func (b *BaseReportSection) SectionTitle() string
SectionTitle returns the display title.
func (*BaseReportSection) StatusMessage ¶
func (b *BaseReportSection) StatusMessage() string
StatusMessage returns the summary message.
func (*BaseReportSection) TopIssues ¶
func (b *BaseReportSection) TopIssues(_ int) []Issue
TopIssues returns nil by default. Override to provide top issues.
type CommitIdentity ¶
type CommitIdentity interface {
Hash() gitlib.Hash
Author() gitlib.Signature
Committer() gitlib.Signature
Message() string
}
CommitIdentity provides commit identification methods.
type CommitLike ¶
type CommitLike interface {
CommitIdentity
CommitParents
Tree() (*gitlib.Tree, error)
Files() (*gitlib.FileIter, error)
File(path string) (*gitlib.File, error)
}
CommitLike is an interface for commit-like objects (real or mock). It composes CommitIdentity and CommitParents with tree/file access.
type CommitMeta ¶
type CommitMeta struct {
Hash string `json:"hash"`
Timestamp string `json:"timestamp"`
Author string `json:"author"`
Tick int `json:"tick"`
}
CommitMeta carries per-commit metadata for time-series construction. Analyzers populate this during Consume() from the analyze.Context.
type CommitParents ¶
CommitParents provides access to parent commits.
type Context ¶
type Context struct {
Time time.Time
Commit CommitLike
Index int
IsMerge bool
// Changes contains the tree diff changes for this commit.
Changes gitlib.Changes
// BlobCache maps blob hashes to cached blobs.
// Populated by the runtime pipeline for efficient blob access.
BlobCache map[gitlib.Hash]*gitlib.CachedBlob
// FileDiffs maps file paths to diff data for modified files.
// Populated by the runtime pipeline using native C diff computation.
FileDiffs map[string]plumbing.FileDiffData
// UASTChanges contains pre-computed UAST changes for this commit.
// Populated by the UAST pipeline stage when enabled.
UASTChanges []uast.Change
}
Context provides information about the current step in the analysis.
type Descriptor ¶
type Descriptor struct {
ID string
Description string
Mode AnalyzerMode
}
Descriptor contains stable analyzer metadata.
func NewDescriptor ¶
func NewDescriptor(mode AnalyzerMode, name, description string) Descriptor
NewDescriptor builds stable analyzer metadata from analyzer name and mode.
type DistributionItem ¶
type DistributionItem struct {
Label string // Category label (e.g., "Simple (1-5)").
Percent float64 // Percentage as 0-1.
Count int // Absolute count.
}
DistributionItem represents a category in a distribution chart.
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory manages registration and execution of static analyzers.
func NewFactory ¶
func NewFactory(analyzers []StaticAnalyzer) *Factory
NewFactory creates a new factory instance.
func (*Factory) RegisterAnalyzer ¶
func (f *Factory) RegisterAnalyzer(analyzer StaticAnalyzer)
RegisterAnalyzer adds an analyzer to the registry.
func (*Factory) RunAnalyzer ¶
RunAnalyzer executes the specified analyzer.
type HistoryAnalyzer ¶
type HistoryAnalyzer interface {
Analyzer
// Core analysis methods.
Initialize(repository *gitlib.Repository) error
// Consumption.
Consume(ctx context.Context, ac *Context) error
// Result handling.
Finalize() (Report, error)
// Branching support.
Fork(n int) []HistoryAnalyzer
Merge(branches []HistoryAnalyzer)
// Formatting/Serialization.
// Format can be: "yaml", "json", or "binary" (protobuf).
Serialize(result Report, format string, writer io.Writer) error
}
HistoryAnalyzer interface defines the contract for history-based analyzers.
type Issue ¶
type Issue struct {
Name string // Item name (e.g., function name).
Location string // File location (e.g., "pkg/foo/bar.go:42").
Value string // Metric value (e.g., "12").
Severity string // "good", "fair", "poor", or "info".
}
Issue represents a problem or item to highlight.
type MergedCommitData ¶
type MergedCommitData struct {
Hash string `json:"hash"`
Timestamp string `json:"timestamp"`
Author string `json:"author"`
Tick int `json:"tick"`
Analyzers map[string]any `json:"-"`
}
MergedCommitData holds merged analyzer data for a single commit.
func (MergedCommitData) MarshalJSON ¶
func (m MergedCommitData) MarshalJSON() ([]byte, error)
MarshalJSON flattens commit metadata and per-analyzer data into a single object: {"hash": "...", "timestamp": "...", "author": "...", "tick": N, "quality": {...}, ...}.
type MergedTimeSeries ¶
type MergedTimeSeries struct {
Version string `json:"version"`
TickSizeHours float64 `json:"tick_size_hours"`
Analyzers []string `json:"analyzers"`
Commits []MergedCommitData `json:"commits"`
}
MergedTimeSeries is the top-level unified time-series output structure.
func BuildMergedTimeSeries ¶
func BuildMergedTimeSeries( reports map[string]Report, commitMeta []CommitMeta, tickSizeHours float64, ) *MergedTimeSeries
BuildMergedTimeSeries builds a unified time-series from multiple analyzer reports. It iterates registered TickExtractors, collects per-commit data from each analyzer, and merges them into MergedCommitData entries ordered by the commit metadata sequence.
type Metric ¶
type Metric struct {
Label string // Display label (e.g., "Total Functions").
Value string // Pre-formatted value (e.g., "156").
}
Metric represents a key-value metric for display.
type MultiAnalyzerTraverser ¶
type MultiAnalyzerTraverser struct {
// contains filtered or unexported fields
}
MultiAnalyzerTraverser manages multiple visitors for UAST traversal.
func NewMultiAnalyzerTraverser ¶
func NewMultiAnalyzerTraverser() *MultiAnalyzerTraverser
NewMultiAnalyzerTraverser creates a new MultiAnalyzerTraverser.
func (*MultiAnalyzerTraverser) RegisterVisitor ¶
func (t *MultiAnalyzerTraverser) RegisterVisitor(v NodeVisitor)
RegisterVisitor registers a visitor to be called during traversal.
func (*MultiAnalyzerTraverser) Traverse ¶
func (t *MultiAnalyzerTraverser) Traverse(root *node.Node)
Traverse starts traversal from the root node.
type NodeVisitor ¶
NodeVisitor defines the interface for UAST visitors.
type Parallelizable ¶
type Parallelizable interface {
// SequentialOnly returns true if this analyzer cannot be parallelized
// (e.g. it tracks cumulative state across all commits).
SequentialOnly() bool
// CPUHeavy returns true if this analyzer's Consume() is CPU-intensive
// (e.g. UAST processing) and benefits from W parallel workers.
// Lightweight analyzers return false and run on the main goroutine
// to avoid fork/merge overhead.
CPUHeavy() bool
// SnapshotPlumbing captures the current plumbing output state.
// Called once per commit after core analyzers have run.
// The returned value is opaque to the framework.
SnapshotPlumbing() PlumbingSnapshot
// ApplySnapshot restores plumbing state from a previously captured snapshot.
// Called on forked copies before Consume().
ApplySnapshot(snapshot PlumbingSnapshot)
// ReleaseSnapshot releases any resources owned by the snapshot
// (e.g. UAST trees). Called once per snapshot after all leaves
// in the worker have consumed it.
ReleaseSnapshot(snapshot PlumbingSnapshot)
}
Parallelizable is optionally implemented by leaf analyzers that support parallel execution via the framework's Fork/Merge worker pool. The framework uses these methods instead of type-switching on concrete types.
type PlotGenerator ¶
type PlotGenerator interface {
GenerateChart(report Report) (components.Charter, error)
}
PlotGenerator interface for analyzers that can generate plots.
type PlotRenderer ¶
type PlotRenderer func(model UnifiedModel, writer io.Writer) error
PlotRenderer is a function that renders a UnifiedModel as a plot to the given writer. It is provided by the renderer package to avoid import cycles.
type PlumbingSnapshot ¶
type PlumbingSnapshot any
PlumbingSnapshot is an opaque snapshot of plumbing state for one commit. The framework treats this as an opaque value; concrete snapshot types are defined in the plumbing package.
type PreparationConfig ¶
type PreparationConfig struct {
// Tick0 is the time of the first commit (for tick calculation).
Tick0 time.Time
// TickSize is the duration of one tick.
TickSize time.Duration
// PeopleDict maps author keys to author IDs.
PeopleDict map[string]int
}
PreparationConfig holds configuration for commit preparation.
type PreparedCommit ¶
type PreparedCommit struct {
Ctx *Context
Changes []*gitlib.Change
Cache map[gitlib.Hash]*gitlib.CachedBlob
FileDiffs map[string]pkgplumbing.FileDiffData
Index int
Err error
// AuthorID is the resolved author identifier.
AuthorID int
// Tick is the time tick for this commit.
Tick int
}
PreparedCommit holds all pre-computed data for a single commit. This is used by the pipelined runner to pass pre-fetched data to analyzers.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry stores analyzer metadata with deterministic ordering.
func NewRegistry ¶
func NewRegistry(static []StaticAnalyzer, history []HistoryAnalyzer) (*Registry, error)
NewRegistry creates a registry from analyzer descriptors.
func (*Registry) All ¶
func (r *Registry) All() []Descriptor
All returns all descriptors in stable order.
func (*Registry) Descriptor ¶
func (r *Registry) Descriptor(id string) (Descriptor, bool)
Descriptor returns analyzer metadata for the given ID.
func (*Registry) ExpandPatterns ¶
ExpandPatterns expands glob patterns against registered analyzer IDs.
func (*Registry) IDsByMode ¶
func (r *Registry) IDsByMode(mode AnalyzerMode) []string
IDsByMode returns IDs for the given mode in stable order.
func (*Registry) SelectedIDs ¶
SelectedIDs returns the analyzer IDs for the given patterns, or all IDs if none specified.
type ReportSection ¶
type ReportSection interface {
// SectionTitle returns the display title (e.g., "COMPLEXITY").
SectionTitle() string
// Score returns a 0-1 score, or ScoreInfoOnly for info-only sections.
Score() float64
// ScoreLabel returns formatted score (e.g., "8/10" or "Info").
ScoreLabel() string
// StatusMessage returns a summary message (e.g., "Good - reasonable complexity").
StatusMessage() string
// KeyMetrics returns ordered key metrics for display.
KeyMetrics() []Metric
// Distribution returns distribution data for bar charts.
Distribution() []DistributionItem
// TopIssues returns the top N issues/items to highlight.
TopIssues(n int) []Issue
// AllIssues returns all issues for verbose mode.
AllIssues() []Issue
}
ReportSection provides a standardized structure for analyzer reports. Analyzers implement this to enable unified rendering.
type ReportSectionProvider ¶
type ReportSectionProvider interface {
CreateReportSection(report Report) ReportSection
}
ReportSectionProvider can create a ReportSection from report data. Analyzers implement this to enable executive summary generation.
type ResultAggregator ¶
ResultAggregator defines the interface for aggregating analyzer results.
type SectionGenerator ¶
SectionGenerator interface for analyzers that can generate page sections.
type SectionRendererFunc ¶
SectionRendererFunc generates plot sections from a raw report for a specific analyzer.
func PlotSectionsFor ¶
func PlotSectionsFor(analyzerID string) SectionRendererFunc
PlotSectionsFor returns the registered section renderer for an analyzer ID, or nil.
type StaticAnalyzer ¶
type StaticAnalyzer interface {
Analyzer
Analyze(root *node.Node) (Report, error)
Thresholds() Thresholds
// Aggregation methods.
CreateAggregator() ResultAggregator
// Formatting methods.
FormatReport(report Report, writer io.Writer) error
FormatReportJSON(report Report, writer io.Writer) error
FormatReportYAML(report Report, writer io.Writer) error
FormatReportPlot(report Report, writer io.Writer) error
FormatReportBinary(report Report, writer io.Writer) error
}
StaticAnalyzer interface defines the contract for UAST-based static analysis.
type StaticRenderer ¶
type StaticRenderer interface {
// SectionsToJSON converts report sections to a JSON-serializable value.
SectionsToJSON(sections []ReportSection) any
// RenderText writes human-readable text output for the given sections.
RenderText(sections []ReportSection, verbose, noColor bool, writer io.Writer) error
// RenderCompact writes single-line-per-section compact output.
RenderCompact(sections []ReportSection, noColor bool, writer io.Writer) error
}
StaticRenderer abstracts section-based rendering to avoid import cycles between the analyze and renderer packages. The renderer package provides the production implementation.
type StaticService ¶
type StaticService struct {
Analyzers []StaticAnalyzer
// Renderer provides section-based output rendering.
// Must be set before calling FormatJSON, FormatText, FormatCompact, or RunAndFormat.
Renderer StaticRenderer
}
StaticService provides a high-level interface for running static analysis.
func NewStaticService ¶
func NewStaticService(analyzers []StaticAnalyzer) *StaticService
NewStaticService creates a StaticService with the given analyzers.
func (*StaticService) AnalyzeFolder ¶
func (svc *StaticService) AnalyzeFolder(ctx context.Context, rootPath string, analyzerList []string) (map[string]Report, error)
AnalyzeFolder runs static analyzers for supported files in a folder tree. Files are discovered sequentially, then analyzed in parallel using a worker pool.
func (*StaticService) AnalyzerNamesByID ¶
func (svc *StaticService) AnalyzerNamesByID(ids []string) ([]string, error)
AnalyzerNamesByID resolves analyzer descriptor IDs to internal names.
func (*StaticService) BuildSections ¶
func (svc *StaticService) BuildSections(results map[string]Report) []ReportSection
BuildSections creates ReportSection instances from results in deterministic order.
func (*StaticService) FindAnalyzer ¶
func (svc *StaticService) FindAnalyzer(name string) StaticAnalyzer
FindAnalyzer finds an analyzer by name.
func (*StaticService) FormatCompact ¶
func (svc *StaticService) FormatCompact(results map[string]Report, noColor bool, writer io.Writer) error
FormatCompact renders analysis results as single-line-per-analyzer compact output.
func (*StaticService) FormatJSON ¶
FormatJSON encodes analysis results as indented JSON.
func (*StaticService) FormatPerAnalyzer ¶
func (svc *StaticService) FormatPerAnalyzer( analyzerNames []string, results map[string]Report, format string, writer io.Writer, ) error
FormatPerAnalyzer renders results using per-analyzer formatters (YAML, plot, or binary).
func (*StaticService) FormatText ¶
func (svc *StaticService) FormatText(results map[string]Report, verbose, noColor bool, writer io.Writer) error
FormatText renders analysis results as human-readable text with optional color and verbosity.
type Thresholds ¶
Thresholds represents color-coded thresholds for multiple metrics Structure: {"metric_name": {"red": value, "yellow": value, "green": value}}.
type TickExtractor ¶
TickExtractor extracts per-commit data from a finalized analyzer report. Returns a map of commit hash (hex string) to a JSON-serializable value representing that analyzer's data for the commit. Returns nil if no per-commit data is available.
func TickExtractorFor ¶
func TickExtractorFor(analyzerFlag string) TickExtractor
TickExtractorFor returns the registered tick extractor for the given flag, or nil.
type UnifiedModel ¶
type UnifiedModel struct {
Version string `json:"version" yaml:"version"`
Analyzers []AnalyzerResult `json:"analyzers" yaml:"analyzers"`
}
UnifiedModel is the canonical intermediate model for run output conversion.
func DecodeBinaryInputModel ¶
func DecodeBinaryInputModel( input []byte, orderedIDs []string, registry *Registry, ) (UnifiedModel, error)
DecodeBinaryInputModel decodes concatenated binary envelopes into a unified model. It first tries to interpret a single envelope as canonical unified JSON and falls back to per-analyzer legacy decoding when that fails.
func DecodeInputModel ¶
func DecodeInputModel( input []byte, inputFormat string, orderedIDs []string, registry *Registry, ) (UnifiedModel, error)
DecodeInputModel dispatches input decoding based on the inputFormat.
func NewUnifiedModel ¶
func NewUnifiedModel(results []AnalyzerResult) UnifiedModel
NewUnifiedModel builds a canonical model from analyzer results.
func ParseUnifiedModelJSON ¶
func ParseUnifiedModelJSON(data []byte) (UnifiedModel, error)
ParseUnifiedModelJSON parses canonical JSON into UnifiedModel.
func (UnifiedModel) Validate ¶
func (m UnifiedModel) Validate() error
Validate ensures canonical model constraints are satisfied.
type VisitorProvider ¶
type VisitorProvider interface {
CreateVisitor() AnalysisVisitor
}
VisitorProvider enables single-pass traversal optimization.