readgo

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2024 License: MIT Imports: 16 Imported by: 0

README

ReadGo

English | 中文

ReadGo is a Go code analysis tool that helps developers understand and navigate Go codebases. It provides functionality for analyzing Go source code, including type information, function signatures, and package dependencies.

Features

  • Project-wide code analysis
  • Type information extraction
  • Function signature analysis
  • Package dependency tracking
  • Interface implementation detection
  • Code structure visualization
  • Cache support for better performance

Installation

Prerequisites
  • Go 1.16 or later
  • Make (optional, for using Makefile commands)
  • golangci-lint (for code linting)
Installing the Tool
  1. Clone the repository:
git clone https://github.com/iamlongalong/readgo.git
cd readgo
  1. Install development tools:
make install-tools
  1. Build the project:
make build

Usage

Basic Commands
// Initialize an analyzer
analyzer := readgo.NewAnalyzer()

// Analyze a file
result, err := analyzer.AnalyzeFile(context.Background(), "main.go")

// Analyze a package
result, err := analyzer.AnalyzePackage(context.Background(), "mypackage")

// Analyze an entire project
result, err := analyzer.AnalyzeProject(context.Background(), ".")

// Find a specific type
typeInfo, err := analyzer.FindType(context.Background(), "mypackage", "MyType")

// Find an interface
interfaceInfo, err := analyzer.FindInterface(context.Background(), "mypackage", "MyInterface")
Development Commands

The project includes a Makefile with common development commands:

# Show all available commands
make help

# Build the project
make build

# Run tests
make test

# Run code checks (format, vet, lint, test)
make check

# Run pre-commit checks
make pre-commit

# Format code
make fmt

# Clean build artifacts
make clean

Configuration

Analyzer Options
analyzer := readgo.NewAnalyzer(
    readgo.WithWorkDir("path/to/workspace"),
    readgo.WithCacheTTL(time.Minute * 5),
)
Cache Configuration

The analyzer includes a caching system to improve performance:

  • Default TTL: 5 minutes
  • Cache can be disabled by setting TTL to 0
  • Cache statistics available via GetCacheStats()

Project Structure

.
├── analyzer.go       # Main analyzer implementation
├── cache.go         # Caching system
├── common.go        # Common utilities
├── errors.go        # Error definitions
├── options.go       # Configuration options
├── reader.go        # Source code reader
├── types.go         # Type definitions
└── validator.go     # Code validation

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run tests and checks (make pre-commit)
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Development Workflow

  1. Make your changes
  2. Run make fmt to format code
  3. Run make check to verify changes
  4. Run make pre-commit before committing
  5. Create pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • The Go team for the excellent go/ast and go/types packages
  • The community for feedback and contributions

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound indicates the requested resource was not found
	ErrNotFound = fmt.Errorf("not found")

	// ErrInvalidInput indicates invalid input parameters
	ErrInvalidInput = fmt.Errorf("invalid input")

	// ErrPermission indicates permission related errors
	ErrPermission = fmt.Errorf("permission denied")
)

Error types for better error handling and context

Functions

This section is empty.

Types

type AnalysisError

type AnalysisError struct {
	Op      string // Operation that failed (e.g., "load package", "parse file")
	Path    string // File or package path where the error occurred
	Wrapped error  // The underlying error
}

AnalysisError represents an error that occurred during code analysis

func (*AnalysisError) Error

func (e *AnalysisError) Error() string

func (*AnalysisError) Unwrap

func (e *AnalysisError) Unwrap() error

type AnalysisResult

type AnalysisResult struct {
	Name       string         `json:"name"`
	Path       string         `json:"path"`
	StartTime  string         `json:"start_time"`
	AnalyzedAt time.Time      `json:"analyzed_at"`
	Types      []TypeInfo     `json:"types,omitempty"`
	Functions  []FunctionInfo `json:"functions,omitempty"`
	Imports    []string       `json:"imports,omitempty"`
}

AnalysisResult represents the result of code analysis

type AnalyzerOptions

type AnalyzerOptions struct {
	// WorkDir is the working directory for the analyzer
	WorkDir string

	// CacheTTL is the time-to-live for cached entries
	// If zero, caching is disabled
	CacheTTL time.Duration

	// MaxCacheSize is the maximum number of entries in each cache type
	// If zero, no limit is applied
	MaxCacheSize int

	// AnalysisTimeout is the timeout for analysis operations
	// If zero, no timeout is applied
	AnalysisTimeout time.Duration

	// EnableConcurrentAnalysis enables concurrent analysis for large projects
	EnableConcurrentAnalysis bool

	// MaxConcurrentAnalysis is the maximum number of concurrent analyses
	// If zero, defaults to runtime.NumCPU()
	MaxConcurrentAnalysis int
}

AnalyzerOptions configures the behavior of the analyzer

func DefaultOptions

func DefaultOptions() *AnalyzerOptions

DefaultOptions returns the default analyzer options

type Cache

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

Cache provides a simple in-memory cache for type information

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache with the given TTL

func (*Cache) GetType

func (c *Cache) GetType(key TypeCacheKey) (*TypeInfo, bool)

GetType retrieves a type from the cache

func (*Cache) SetType

func (c *Cache) SetType(key TypeCacheKey, info *TypeInfo)

SetType stores a type in the cache

func (*Cache) Stats

func (c *Cache) Stats() map[string]interface{}

Stats returns cache statistics

type CodeAnalyzer

type CodeAnalyzer interface {
	// FindType finds a specific type in the given package
	FindType(ctx context.Context, pkgPath, typeName string) (*TypeInfo, error)

	// FindInterface finds a specific interface in the given package
	FindInterface(ctx context.Context, pkgPath, interfaceName string) (*TypeInfo, error)

	// FindFunction finds a specific function in the given package
	FindFunction(ctx context.Context, pkgPath, funcName string) (*TypeInfo, error)

	// AnalyzeFile analyzes a specific Go source file
	AnalyzeFile(ctx context.Context, filePath string) (*AnalysisResult, error)

	// AnalyzePackage analyzes a Go package
	AnalyzePackage(ctx context.Context, pkgPath string) (*AnalysisResult, error)

	// AnalyzeProject analyzes a Go project at the specified path
	AnalyzeProject(ctx context.Context, projectPath string) (*AnalysisResult, error)
}

CodeAnalyzer defines the interface for analyzing Go code

type DefaultAnalyzer

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

DefaultAnalyzer implements the CodeAnalyzer interface

func NewAnalyzer

func NewAnalyzer(opts ...Option) *DefaultAnalyzer

NewAnalyzer creates a new DefaultAnalyzer instance

func (*DefaultAnalyzer) AnalyzeFile

func (a *DefaultAnalyzer) AnalyzeFile(ctx context.Context, filePath string) (*AnalysisResult, error)

AnalyzeFile analyzes a specific Go source file

func (*DefaultAnalyzer) AnalyzePackage

func (a *DefaultAnalyzer) AnalyzePackage(ctx context.Context, pkgPath string) (*AnalysisResult, error)

AnalyzePackage analyzes a Go package

func (*DefaultAnalyzer) AnalyzeProject

func (a *DefaultAnalyzer) AnalyzeProject(ctx context.Context, projectPath string) (*AnalysisResult, error)

AnalyzeProject analyzes a Go project at the specified path

func (*DefaultAnalyzer) FindInterface

func (a *DefaultAnalyzer) FindInterface(ctx context.Context, pkgPath, interfaceName string) (result *TypeInfo, err error)

FindInterface finds an interface in the given package

func (*DefaultAnalyzer) FindType

func (a *DefaultAnalyzer) FindType(ctx context.Context, pkgPath, typeName string) (result *TypeInfo, err error)

FindType finds a type in the given package

func (*DefaultAnalyzer) GetCacheStats

func (a *DefaultAnalyzer) GetCacheStats() map[string]interface{}

GetCacheStats returns cache statistics

type DefaultReader

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

DefaultReader implements SourceReader

func NewDefaultReader

func NewDefaultReader() *DefaultReader

NewDefaultReader creates a new DefaultReader instance

func (*DefaultReader) GetFileTree

func (r *DefaultReader) GetFileTree(ctx context.Context, root string, opts TreeOptions) (*FileTreeNode, error)

GetFileTree returns the file tree starting from the given root

func (*DefaultReader) GetPackageFiles

func (r *DefaultReader) GetPackageFiles(ctx context.Context, pkgPath string, opts TreeOptions) ([]*FileTreeNode, error)

GetPackageFiles returns all files in a package

func (*DefaultReader) ReadFileWithFunctions added in v0.2.1

func (r *DefaultReader) ReadFileWithFunctions(ctx context.Context, path string) (*FileContent, error)

ReadFileWithFunctions reads a source file and returns its content along with function positions

func (*DefaultReader) ReadSourceFile

func (r *DefaultReader) ReadSourceFile(ctx context.Context, path string, opts ReadOptions) ([]byte, error)

ReadSourceFile reads a source file with the given options

func (*DefaultReader) SearchFiles

func (r *DefaultReader) SearchFiles(ctx context.Context, pattern string, opts TreeOptions) ([]*FileTreeNode, error)

SearchFiles searches for files matching the given pattern

func (*DefaultReader) WithWorkDir

func (r *DefaultReader) WithWorkDir(dir string) *DefaultReader

WithWorkDir sets the working directory for the reader

type DefaultValidator

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

DefaultValidator implements the code validator

func NewValidator

func NewValidator(baseDir string) *DefaultValidator

NewValidator creates a new validator

func (*DefaultValidator) ValidateFile

func (v *DefaultValidator) ValidateFile(ctx context.Context, filePath string) (*ValidationResult, error)

ValidateFile validates a Go source file

func (*DefaultValidator) ValidatePackage

func (v *DefaultValidator) ValidatePackage(ctx context.Context, pkgPath string) (*ValidationResult, error)

ValidatePackage validates a Go package

func (*DefaultValidator) ValidateProject

func (v *DefaultValidator) ValidateProject(ctx context.Context) (*ValidationResult, error)

ValidateProject validates the entire project

type FileContent added in v0.2.1

type FileContent struct {
	Content   []byte             `json:"content"`   // File content
	Functions []FunctionPosition `json:"functions"` // Function positions
}

FileContent represents the content of a file with function positions

type FileTreeNode

type FileTreeNode struct {
	Name     string          `json:"name"`
	Path     string          `json:"path"`
	Type     string          `json:"type"` // "file" or "directory"
	Size     int64           `json:"size,omitempty"`
	ModTime  time.Time       `json:"mod_time,omitempty"`
	Children []*FileTreeNode `json:"children,omitempty"`
}

FileTreeNode represents a node in the file tree

type FileType

type FileType string

FileType represents the type of files to include in the analysis

const (
	// FileTypeAll includes all file types
	FileTypeAll FileType = "all"
	// FileTypeGo includes only Go files
	FileTypeGo FileType = "go"
	// FileTypeTest includes only test files
	FileTypeTest FileType = "test"
	// FileTypeGenerated includes only generated files
	FileTypeGenerated FileType = "generated"
)

type FunctionInfo

type FunctionInfo struct {
	Name       string `json:"name"`
	Package    string `json:"package"`
	IsExported bool   `json:"is_exported"`
}

FunctionInfo represents information about a Go function

type FunctionPosition added in v0.2.1

type FunctionPosition struct {
	Name      string `json:"name"`       // Function name
	StartLine int    `json:"start_line"` // Starting line number
	EndLine   int    `json:"end_line"`   // Ending line number
}

FunctionPosition represents the position of a function in the source code

type Option

type Option func(*AnalyzerOptions)

Option is a function that configures AnalyzerOptions

func WithAnalysisTimeout

func WithAnalysisTimeout(timeout time.Duration) Option

WithAnalysisTimeout sets the analysis timeout

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) Option

WithCacheTTL sets the cache TTL

func WithConcurrentAnalysis

func WithConcurrentAnalysis(enable bool) Option

WithConcurrentAnalysis enables or disables concurrent analysis

func WithMaxCacheSize

func WithMaxCacheSize(size int) Option

WithMaxCacheSize sets the maximum cache size

func WithMaxConcurrentAnalysis

func WithMaxConcurrentAnalysis(max int) Option

WithMaxConcurrentAnalysis sets the maximum number of concurrent analyses

func WithWorkDir

func WithWorkDir(dir string) Option

WithWorkDir sets the working directory

type PackageError

type PackageError struct {
	Package string   // Package path
	Op      string   // Operation that failed
	Errors  []string // List of errors
	Wrapped error    // The underlying error
}

PackageError represents an error that occurred during package operations

func (*PackageError) Error

func (e *PackageError) Error() string

func (*PackageError) Unwrap

func (e *PackageError) Unwrap() error

type ReadOptions

type ReadOptions struct {
	IncludeComments bool `json:"include_comments"`
	StripSpaces     bool `json:"strip_spaces"`
}

ReadOptions represents options for reading source files

type SourceReader

type SourceReader interface {
	// GetFileTree returns the file tree starting from the given root
	GetFileTree(ctx context.Context, root string, opts TreeOptions) (*FileTreeNode, error)

	// ReadSourceFile reads a source file with the specified options
	ReadSourceFile(ctx context.Context, path string, opts ReadOptions) ([]byte, error)

	// GetPackageFiles returns all files in a package
	GetPackageFiles(ctx context.Context, pkgPath string, opts TreeOptions) ([]*FileTreeNode, error)

	// SearchFiles searches for files matching the given pattern
	SearchFiles(ctx context.Context, pattern string, opts TreeOptions) ([]*FileTreeNode, error)
}

SourceReader defines the interface for reading Go source code

func NewSourceReader added in v0.2.1

func NewSourceReader(workDir string) SourceReader

NewSourceReader creates a new DefaultReader instance

type TreeOptions

type TreeOptions struct {
	FileTypes       FileType `json:"file_types"`
	ExcludePatterns []string `json:"exclude_patterns,omitempty"`
	IncludePatterns []string `json:"include_patterns,omitempty"`
}

TreeOptions represents options for file tree operations

type TypeCacheKey

type TypeCacheKey struct {
	Package  string
	TypeName string
	Kind     string
}

TypeCacheKey is the key used for caching type information

type TypeInfo

type TypeInfo struct {
	Name       string `json:"name"`
	Package    string `json:"package"`
	Type       string `json:"type"`
	IsExported bool   `json:"is_exported"`
}

TypeInfo represents information about a Go type

type TypeLookupError

type TypeLookupError struct {
	TypeName string // Name of the type being looked up
	Package  string // Package where the lookup was performed
	Kind     string // Kind of type (e.g., "interface", "struct")
	Wrapped  error  // The underlying error
}

TypeLookupError represents an error that occurred during type lookup

func (*TypeLookupError) Error

func (e *TypeLookupError) Error() string

func (*TypeLookupError) Unwrap

func (e *TypeLookupError) Unwrap() error

type ValidationError

type ValidationError struct {
	File    string // File where the error occurred
	Line    int    // Line number where the error occurred
	Column  int    // Column number where the error occurred
	Message string // Error message
	Wrapped error  // The underlying error
}

ValidationError represents an error that occurred during code validation

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type ValidationResult

type ValidationResult struct {
	Name       string              `json:"name"`
	Path       string              `json:"path"`
	StartTime  string              `json:"start_time"`
	AnalyzedAt time.Time           `json:"analyzed_at"`
	Errors     []string            `json:"errors,omitempty"`
	Warnings   []ValidationWarning `json:"warnings,omitempty"`
}

ValidationResult represents the result of code validation

type ValidationWarning

type ValidationWarning struct {
	Type    string `json:"type"`
	Message string `json:"message"`
	File    string `json:"file,omitempty"`
	Line    int    `json:"line,omitempty"`
	Column  int    `json:"column,omitempty"`
}

ValidationWarning represents a warning during validation

type Validator

type Validator interface {
	// ValidateFile validates a specific Go source file
	ValidateFile(ctx context.Context, filePath string) (*ValidationResult, error)

	// ValidatePackage validates a Go package
	ValidatePackage(ctx context.Context, pkgPath string) (*ValidationResult, error)

	// ValidateProject validates the entire project
	ValidateProject(ctx context.Context) (*ValidationResult, error)
}

Validator defines the interface for validating Go code

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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