Documentation
¶
Overview ¶
Package parser extracts metrics from Go source code using the go/ast package.
The parser analyzes Go source files to extract: - File-level metrics (total lines, code lines, comment lines, blank lines) - Function-level metrics (length, parameters, return statements, nesting depth) - Cyclomatic complexity using McCabe's algorithm - Import statements and package information
Usage ¶
Parse a single file:
fset := token.NewFileSet()
metrics, err := parser.ParseFile(fset, "main.go")
if err != nil {
log.Fatal(err)
}
Parse an entire directory:
excludePatterns := []string{"vendor/**", "**/*_test.go"}
metrics, errs := parser.ParseDirectory("./src", excludePatterns)
for _, err := range errs {
log.Printf("Parse error: %v", err)
}
The parser uses glob patterns for exclusions and supports: - ** (match any number of directories) - * (match any characters in a single path component) - ? (match a single character)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ASTParser ¶
type ASTParser struct{}
ASTParser implements Parser using Go's AST (Abstract Syntax Tree) packages.
This implementation uses go/parser to build an AST and go/ast to traverse it, extracting structural metrics without requiring the code to compile or run.
func (*ASTParser) ParseDirectory ¶
func (p *ASTParser) ParseDirectory(rootPath string, excludePatterns []string, statusReporter status.Reporter) ([]*FileMetrics, []error)
ParseDirectory recursively discovers and parses all Go files in a directory.
Uses filepath.Walk to traverse the directory tree, parsing all .go files that don't match the exclude patterns. Patterns support glob syntax:
- vendor/** - exclude vendor directory and subdirectories
- **/*_test.go - exclude all test files
- **/testdata/** - exclude testdata directories
This method is designed to be fault-tolerant:
- Parse errors for individual files are collected but don't stop processing
- Directory access errors are logged and skipped
- Returns metrics for all successfully parsed files
The excludePatterns are matched against paths relative to rootPath.
func (*ASTParser) ParseFile ¶
func (p *ASTParser) ParseFile(path string) (*FileMetrics, error)
ParseFile parses a single Go file and extracts comprehensive metrics.
Uses go/parser.ParseFile to build an AST, then walks the tree to extract:
- File-level metrics (line counts, imports, package name)
- Function-level metrics (size, complexity, parameters, returns)
Returns an error if the file doesn't exist, isn't a .go file, or contains syntax errors that prevent parsing.
type FileMetrics ¶
type FileMetrics struct {
FilePath string // Absolute or relative path to the file
PackageName string // Package declaration
TotalLines int // Total lines in the file
CodeLines int // Lines with actual code (excluding blank and comments)
CommentLines int // Lines with comments
BlankLines int // Blank lines
Functions []*FunctionMetrics // All functions/methods in the file
Imports []string // Import paths
}
FileMetrics contains comprehensive metrics extracted from a single Go source file.
This type aggregates both file-level and function-level metrics obtained through AST parsing. It provides a complete picture of file structure including:
- Line counts (total, code, comments, blank)
- Package information
- Import dependencies
- All functions and methods defined in the file
FileMetrics is the primary data structure returned by ParseFile and used throughout the analysis pipeline.
func (*FileMetrics) CodeRatio ¶
func (fm *FileMetrics) CodeRatio() float64
CodeRatio calculates the ratio of code lines to total lines.
Returns a value between 0.0 and 1.0 representing the proportion of the file that consists of actual code (excluding comments and blank lines).
Returns 0.0 for empty files.
func (*FileMetrics) CommentRatio ¶
func (fm *FileMetrics) CommentRatio() float64
CommentRatio calculates the ratio of comment lines to total lines.
Returns a value between 0.0 and 1.0 representing the proportion of the file that consists of comments. A higher ratio indicates better documentation.
Recommended minimum ratio is 0.15 (15%). Returns 0.0 for empty files.
type FunctionMetrics ¶
type FunctionMetrics struct {
Name string // Function name
ReceiverType string // Empty if not a method, otherwise the receiver type
StartLine int // Line number where function starts
EndLine int // Line number where function ends
Lines int // Total lines in function body
Parameters int // Number of parameters
ReturnValues int // Number of return values
Complexity int // Simple cyclomatic complexity (Phase 1: basic count)
}
FunctionMetrics contains comprehensive metrics for a single function or method.
This type captures both structural and complexity metrics:
- Identity: name, receiver type (for methods), location
- Size: line count and location within file
- Signature: parameter count, return value count
- Complexity: cyclomatic complexity using McCabe's method
Methods can be identified by checking IsMethod() or examining ReceiverType. The FullName() method provides a consistent naming scheme for both functions and methods.
func (*FunctionMetrics) FullName ¶
func (fm *FunctionMetrics) FullName() string
FullName returns the fully qualified function name including receiver for methods.
For methods, returns "ReceiverType.FunctionName" (e.g., "*Parser.ParseFile"). For standalone functions, returns just the function name (e.g., "main").
This provides a consistent naming scheme for reporting and issue tracking.
func (*FunctionMetrics) IsMethod ¶
func (fm *FunctionMetrics) IsMethod() bool
IsMethod returns true if this function is a method (has a receiver).
Methods in Go are functions with a receiver type. This helper makes it easy to distinguish between standalone functions and methods when analyzing code.
type Parser ¶
type Parser interface {
// ParseFile parses a single Go source file and returns its metrics.
//
// The path must point to a valid .go file. Returns FileMetrics containing:
// - Line counts (total, code, comments, blank)
// - Package information
// - Import list
// - Function/method metrics (size, complexity, signature)
//
// Returns an error if:
// - path is not a .go file
// - file doesn't exist
// - file contains syntax errors
ParseFile(path string) (*FileMetrics, error)
// ParseDirectory recursively parses all Go files in a directory tree.
//
// Discovers and parses all .go files under the specified path, excluding
// files and directories matching the excludePatterns (glob patterns).
//
// The statusReporter parameter is used to report parsing progress.
//
// This method is fault-tolerant: parse errors for individual files are
// collected but don't stop processing. Returns:
// - metrics: FileMetrics for all successfully parsed files
// - errors: parse errors for files that failed (empty if all succeeded)
//
// Common exclude patterns: vendor/**, **/*_test.go, **/testdata/**
ParseDirectory(path string, excludePatterns []string, statusReporter status.Reporter) ([]*FileMetrics, []error)
}
Parser defines the interface for parsing Go source files and extracting metrics.
Implementations use Go's ast, parser, and token packages to analyze source code structure and calculate metrics without executing the code.