Documentation
¶
Index ¶
- Constants
- func Implements(structCandidate *scanner.TypeInfo, interfaceDef *scanner.TypeInfo, ...) bool
- func ResolvePath(ctx context.Context, path string) (string, error)
- func WriteFile(ctx context.Context, path string, data []byte, perm os.FileMode) error
- type Config
- type ConstantInfo
- type ContextKey
- type FileWriter
- type FunctionInfo
- type GoFile
- type ImportManager
- type ModuleWalker
- func (w *ModuleWalker) BuildReverseDependencyMap(ctx context.Context) (map[string][]string, error)
- func (w *ModuleWalker) FindImporters(ctx context.Context, targetImportPath string) ([]*PackageImports, error)
- func (w *ModuleWalker) FindImportersAggressively(ctx context.Context, targetImportPath string) ([]*PackageImports, error)
- func (w *ModuleWalker) ScanPackageImports(ctx context.Context, importPath string) (*scanner.PackageImports, error)
- func (w *ModuleWalker) Walk(ctx context.Context, rootImportPath string, visitor Visitor) error
- type Package
- type PackageDirectory
- type PackageImports
- type Scanner
- func (s *Scanner) BuildImportLookup(file *ast.File) map[string]string
- func (s *Scanner) FindSymbolDefinitionLocation(ctx context.Context, symbolFullName string) (string, error)
- func (s *Scanner) FindSymbolInPackage(ctx context.Context, importPath string, symbolName string) (*scanner.PackageInfo, error)
- func (s *Scanner) Fset() *token.FileSet
- func (s *Scanner) ListExportedSymbols(ctx context.Context, pkgPath string) ([]string, error)
- func (s *Scanner) Locator() *locator.Locator
- func (s *Scanner) LookupOverride(qualifiedName string) (*scanner.TypeInfo, bool)
- func (s *Scanner) ModulePath() string
- func (s *Scanner) ResolveType(ctx context.Context, fieldType *scanner.FieldType) (*scanner.TypeInfo, error)
- func (s *Scanner) RootDir() string
- func (s *Scanner) SaveSymbolCache(ctx context.Context) error
- func (s *Scanner) Scan(patterns ...string) ([]*Package, error)
- func (s *Scanner) ScanFiles(ctx context.Context, filePaths []string) (*scanner.PackageInfo, error)
- func (s *Scanner) ScanPackage(ctx context.Context, pkgPath string) (*scanner.PackageInfo, error)
- func (s *Scanner) ScanPackageByImport(ctx context.Context, importPath string) (*scanner.PackageInfo, error)
- func (s *Scanner) ScanPackageByPos(ctx context.Context, pos token.Pos) (*scanner.PackageInfo, error)
- func (s *Scanner) ScannerForSymgo() (*scanner.Scanner, error)
- func (s *Scanner) SetExternalTypeOverrides(ctx context.Context, overrides scanner.ExternalTypeOverride)
- func (s *Scanner) TypeInfoFromExpr(ctx context.Context, expr ast.Expr, currentTypeParams []*scanner.TypeParamInfo, ...) *scanner.FieldType
- func (s *Scanner) UnscannedGoFiles(packagePathOrImportPath string) ([]string, error)
- type ScannerOption
- func WithDryRun(dryRun bool) ScannerOption
- func WithExternalTypeOverrides(overrides scanner.ExternalTypeOverride) ScannerOption
- func WithGoModuleResolver() ScannerOption
- func WithIncludeTests(include bool) ScannerOption
- func WithInspect(inspect bool) ScannerOption
- func WithLogger(logger *slog.Logger) ScannerOption
- func WithOverlay(overlay scanner.Overlay) ScannerOption
- func WithWorkDir(path string) ScannerOption
- type TypeInfo
- type Visitor
Constants ¶
const ( StructKind = scanner.StructKind AliasKind = scanner.AliasKind FuncKind = scanner.FuncKind InterfaceKind = scanner.InterfaceKind // Ensure InterfaceKind is available )
Re-export scanner kinds for convenience.
const ( // FileWriterKey is the context key for the file writer interceptor. FileWriterKey = ContextKey("fileWriter") )
Variables ¶
This section is empty.
Functions ¶
func Implements ¶
func Implements(structCandidate *scanner.TypeInfo, interfaceDef *scanner.TypeInfo, pkgInfo *scanner.PackageInfo) bool
Implements checks if a struct type implements an interface type within the context of a package. It requires the PackageInfo to look up methods of the structCandidate.
func ResolvePath ¶
ResolvePath converts a file path to a full Go package path. If the path exists on the filesystem, it is treated as a file path and resolved against the module's go.mod file. If it does not exist, it is assumed to be a package path and is returned as-is, unless it has a relative path prefix (like `./`), in which case an error is returned.
This function is a facade for `locator.ResolvePkgPath`.
Types ¶
type Config ¶ added in v0.0.2
type Config struct { IncludeTests bool DryRun bool Inspect bool Logger *slog.Logger // contains filtered or unexported fields }
Config holds shared configuration and state for both Scanner and ModuleWalker. It is intended to be embedded in both structs.
type ConstantInfo ¶
type ConstantInfo = scanner.ConstantInfo
ConstantInfo is an alias for scanner.ConstantInfo.
type ContextKey ¶
type ContextKey string
ContextKey is a private type for context keys to avoid collisions.
type FileWriter ¶
type FileWriter interface {
WriteFile(ctx context.Context, path string, data []byte, perm os.FileMode) error
}
FileWriter is an interface for writing files, allowing for interception during tests.
type FunctionInfo ¶
type FunctionInfo = scanner.FunctionInfo
FunctionInfo is an alias for scanner.FunctionInfo.
type GoFile ¶
type GoFile struct { PackageName string // PackageName is the name of the package (e.g., "main", "models"). // Imports is a map of import path to alias. // If an alias is not needed, the alias should be an empty string. // Example: // Imports = map[string]string{ // "fmt": "", // for `import "fmt"` // "custom_errors": "errors", // for `import errors "custom_errors"` // "github.com/pkg/errors": "", // for `import "github.com/pkg/errors"` // } Imports map[string]string CodeSet string // CodeSet is the body of the Go code to be generated. }
GoFile represents a Go source file to be generated.
type ImportManager ¶
type ImportManager struct {
// contains filtered or unexported fields
}
ImportManager helps manage import statements for generated Go code.
func NewImportManager ¶
func NewImportManager(currentPkgInfo *scanner.PackageInfo) *ImportManager
NewImportManager creates a new ImportManager. currentPkgInfo is the package information for the file being generated. If currentPkgInfo is nil, the ImportManager assumes no specific current package context.
func (*ImportManager) Add ¶
func (im *ImportManager) Add(path string, requestedAlias string) string
Add registers an import path and its desired alias. It handles conflicts by adjusting aliases if necessary. Returns the actual alias that should be used for the package. If the path is the current package's path, it returns an empty string (no alias needed for qualification).
func (*ImportManager) Imports ¶
func (im *ImportManager) Imports() map[string]string
Imports returns a copy of the map of import paths to aliases for use in GoFile. It excludes entries where the alias is empty, as those typically don't need an explicit import line (e.g., the current package itself if it were ever added with an empty alias, though Add prevents this for currentPackagePath).
func (*ImportManager) Qualify ¶
func (im *ImportManager) Qualify(packagePath string, typeName string) string
Qualify returns the qualified type name (e.g., "alias.TypeName" or "TypeName"). It ensures the package path is registered with an alias. If packagePath is empty or matches currentPackagePath, typeName is returned as is.
type ModuleWalker ¶ added in v0.0.2
type ModuleWalker struct { *Config // contains filtered or unexported fields }
ModuleWalker is responsible for lightweight, dependency-focused scanning operations. It primarily deals with parsing package imports and building dependency graphs, without parsing the full details of type and function bodies.
func (*ModuleWalker) BuildReverseDependencyMap ¶ added in v0.0.2
BuildReverseDependencyMap scans the entire module to build a map of reverse dependencies. The key of the map is an import path, and the value is a list of packages that import it. The result is cached within the scanner instance.
func (*ModuleWalker) FindImporters ¶ added in v0.0.2
func (w *ModuleWalker) FindImporters(ctx context.Context, targetImportPath string) ([]*PackageImports, error)
FindImporters scans the entire module to find packages that import the targetImportPath. It performs an efficient, imports-only scan of all potential package directories in the module. The result is a list of packages that have a direct dependency on the target.
func (*ModuleWalker) FindImportersAggressively ¶ added in v0.0.2
func (w *ModuleWalker) FindImportersAggressively(ctx context.Context, targetImportPath string) ([]*PackageImports, error)
FindImportersAggressively scans the module using `git grep` to quickly find files that likely import the targetImportPath, then confirms them. This can be much faster than walking the entire directory structure in large repositories. A git repository is required.
func (*ModuleWalker) ScanPackageImports ¶ added in v0.0.2
func (w *ModuleWalker) ScanPackageImports(ctx context.Context, importPath string) (*scanner.PackageImports, error)
ScanPackageImports scans a single Go package identified by its import path, parsing only the package clause and import declarations for efficiency. It returns a lightweight PackageImports struct containing the package name and a list of its direct dependencies. Results are cached in memory for the lifetime of the ModuleWalker instance.
func (*ModuleWalker) Walk ¶ added in v0.0.2
Walk performs a dependency graph traversal starting from a root import path. It uses the efficient ScanPackageImports method to fetch dependencies at each step. The provided Visitor's Visit method is called for each discovered package, allowing the caller to inspect the package and control which of its dependencies are followed next.
type Package ¶
type Package = scanner.PackageInfo
Package is an alias for scanner.PackageInfo, representing all the extracted information from a single package.
type PackageDirectory ¶
type PackageDirectory struct { Path string // Path is the directory path of the package. DefaultPackageName string // DefaultPackageName is used if GoFile.PackageName is empty. Overwrite bool // Overwrite specifies if existing files should be overwritten. Defaults to true. }
PackageDirectory represents a directory where Go files will be saved.
func NewPackageDirectory ¶
func NewPackageDirectory(path string, defaultPackageName string) *PackageDirectory
NewPackageDirectory creates a new PackageDirectory with default Overwrite behavior (true).
func (*PackageDirectory) SaveGoFile ¶
SaveGoFile generates and saves a Go source file. It formats the source code and handles imports. filename is the complete name of the file to be saved (e.g., "models_deriving.go").
type PackageImports ¶
type PackageImports = scanner.PackageImports
PackageImports is an alias for scanner.PackageImports.
type Scanner ¶
type Scanner struct { *Config CachePath string ExternalTypeOverrides scanner.ExternalTypeOverride // Walker is responsible for lightweight, dependency-focused scanning operations. Walker *ModuleWalker // contains filtered or unexported fields }
Scanner is the main entry point for the type scanning library. It combines a locator for finding packages, a scanner for parsing them, and caches for improving performance over multiple calls. Scanner instances are stateful regarding which files have been visited (parsed).
func New ¶
func New(options ...ScannerOption) (*Scanner, error)
New creates a new Scanner. It finds the module root starting from the given path. It also initializes an empty set of visited files for this scanner instance.
func (*Scanner) BuildImportLookup ¶ added in v0.0.2
BuildImportLookup creates a map of local import names to their full package paths for a given file.
func (*Scanner) FindSymbolDefinitionLocation ¶
func (s *Scanner) FindSymbolDefinitionLocation(ctx context.Context, symbolFullName string) (string, error)
FindSymbolDefinitionLocation attempts to find the absolute file path where a given symbol is defined. The `symbolFullName` should be in the format "package/import/path.SymbolName".
It first checks the persistent symbol cache (if enabled and loaded). If not found in the cache, it triggers a scan of the relevant package (using `ScanPackageByImport`) to populate caches and then re-checks. Finally, it inspects the `PackageInfo` obtained from the scan.
func (*Scanner) FindSymbolInPackage ¶
func (s *Scanner) FindSymbolInPackage(ctx context.Context, importPath string, symbolName string) (*scanner.PackageInfo, error)
FindSymbolInPackage searches for a specific symbol within a package by scanning its files one by one. It only scans files that have not yet been visited by this scanner instance. If the symbol is found, it returns a cumulative PackageInfo of all files scanned in the package up to that point and marks the file as visited. If the symbol is not found after checking all unscanned files, it returns an error.
func (*Scanner) ListExportedSymbols ¶
ListExportedSymbols scans a package by its import path and returns a list of all its exported top-level symbol names (functions, types, and constants).
func (*Scanner) LookupOverride ¶
LookupOverride checks if a fully qualified type name exists in the external type override map.
func (*Scanner) ModulePath ¶
ModulePath returns the module path from the scanner's locator.
func (*Scanner) ResolveType ¶
func (s *Scanner) ResolveType(ctx context.Context, fieldType *scanner.FieldType) (*scanner.TypeInfo, error)
ResolveType starts the type resolution process for a given field type. It's the public entry point for resolving types. It prepares the context with necessary loggers and flags for the entire resolution chain.
func (*Scanner) SaveSymbolCache ¶
SaveSymbolCache saves the symbol cache to disk if CachePath is set.
func (*Scanner) Scan ¶
Scan scans Go packages based on the provided patterns. Each pattern can be a directory path or a file path relative to the scanner's workDir. It returns a list of scanned packages.
func (*Scanner) ScanFiles ¶
ScanFiles scans a specified set of Go files.
File paths in the `filePaths` argument can be provided in three forms:
- Absolute path (e.g., "/path/to/your/project/pkg/file.go").
- Path relative to the current working directory (CWD) (e.g., "pkg/file.go").
- Module-qualified path (e.g., "github.com/your/module/pkg/file.go"), which is resolved using the Scanner's associated module information (from go.mod).
All provided file paths, after resolution, must belong to the same directory, effectively meaning they must be part of the same Go package.
This function only parses files that have not been previously visited (parsed) by this specific Scanner instance (tracked in `s.visitedFiles`).
The returned `scanner.PackageInfo` contains information derived *only* from the files that were newly parsed in *this specific call*. If all specified files were already visited, the `PackageInfo.Files` list (and consequently Types, Functions, etc.) will be empty, though `Path` and `ImportPath` will be set according to the files' package.
Results from `ScanFiles` are *not* stored in the main package cache (`s.packageCache`) because they represent partial package information. However, the global symbol cache (`s.symbolCache`), if enabled, *is* updated with symbols from the newly parsed files. Files parsed by this function are marked as visited in `s.visitedFiles`.
func (*Scanner) ScanPackage ¶
ScanPackage scans a single package at a given directory path (absolute or relative to CWD). It parses all .go files (excluding _test.go) in that directory that have not yet been visited (parsed) by this Scanner instance. The returned PackageInfo contains information derived ONLY from the files parsed in THIS specific call. If no unvisited files are found in the package, the returned PackageInfo will be minimal (e.g., Path and ImportPath set, but no types/functions unless a previous cached version for the entire package is returned). The result of this call (representing the newly parsed files, or a prior cached full result if no new files were parsed and cache existed) is stored in an in-memory package cache (s.packageCache) for subsequent calls to ScanPackage or ScanPackageByImport for the same import path. The global symbol cache (s.symbolCache), if enabled, is updated with symbols from the newly parsed files.
func (*Scanner) ScanPackageByImport ¶
func (s *Scanner) ScanPackageByImport(ctx context.Context, importPath string) (*scanner.PackageInfo, error)
ScanPackageByImport scans a single Go package identified by its import path.
This function resolves the import path to a directory using the Scanner's locator. It then attempts to parse all .go files (excluding _test.go files) in that directory that have not yet been visited by this Scanner instance (`s.visitedFiles`). The selection of files to parse may also be influenced by the state of the symbol cache (`s.symbolCache`), if enabled, to avoid re-parsing unchanged files for which symbol information is already cached and deemed valid.
The returned `scanner.PackageInfo` contains information derived from the files parsed or processed in *this specific call*.
The result of this call is stored in an in-memory package cache (`s.packageCache`) and is intended to represent the Scanner's current understanding of the package, which might be based on a full parse of unvisited files or a combination of cached data and newly parsed information. The global symbol cache (`s.symbolCache`), if enabled, is updated with symbols from any newly parsed files. Files parsed by this function are marked as visited in `s.visitedFiles`.
func (*Scanner) ScanPackageByPos ¶ added in v0.0.2
func (s *Scanner) ScanPackageByPos(ctx context.Context, pos token.Pos) (*scanner.PackageInfo, error)
ScanPackageByPos finds and scans the package containing the given token.Pos.
func (*Scanner) ScannerForSymgo ¶ added in v0.0.2
ScannerForSymgo is a temporary helper for tests to access the internal scanner. TODO: Refactor evaluator to use the top-level goscan.Scanner instead.
func (*Scanner) SetExternalTypeOverrides ¶
func (s *Scanner) SetExternalTypeOverrides(ctx context.Context, overrides scanner.ExternalTypeOverride)
SetExternalTypeOverrides sets the external type override map for the scanner.
func (*Scanner) TypeInfoFromExpr ¶ added in v0.0.2
func (s *Scanner) TypeInfoFromExpr(ctx context.Context, expr ast.Expr, currentTypeParams []*scanner.TypeParamInfo, info *scanner.PackageInfo, importLookup map[string]string) *scanner.FieldType
TypeInfoFromExpr resolves an AST expression that represents a type into a FieldType.
func (*Scanner) UnscannedGoFiles ¶
UnscannedGoFiles returns a list of absolute paths to .go files (and optionally _test.go files) within the specified package that have not yet been visited (parsed) by this Scanner instance.
The `packagePathOrImportPath` argument can be:
- An absolute directory path to the package.
- A directory path relative to the current working directory (CWD).
- A Go import path (e.g., "github.com/your/module/pkg"), which will be resolved to a directory using the Scanner's locator.
This method lists all relevant .go files in the identified package directory and filters out those already present in the Scanner's `visitedFiles` set. It is useful for discovering which files in a package still need to be processed if performing iterative scanning.
type ScannerOption ¶
ScannerOption is a function that configures a Scanner.
func WithDryRun ¶
func WithDryRun(dryRun bool) ScannerOption
WithDryRun enables or disables dry-run mode.
func WithExternalTypeOverrides ¶
func WithExternalTypeOverrides(overrides scanner.ExternalTypeOverride) ScannerOption
WithExternalTypeOverrides sets the external type override map for the scanner.
func WithGoModuleResolver ¶
func WithGoModuleResolver() ScannerOption
WithGoModuleResolver enables the scanner to find packages in the Go module cache and GOROOT.
func WithIncludeTests ¶
func WithIncludeTests(include bool) ScannerOption
WithIncludeTests includes test files in the scan.
func WithInspect ¶
func WithInspect(inspect bool) ScannerOption
WithInspect enables or disables inspect mode.
func WithLogger ¶
func WithLogger(logger *slog.Logger) ScannerOption
WithLogger sets the logger for the scanner.
func WithOverlay ¶
func WithOverlay(overlay scanner.Overlay) ScannerOption
WithOverlay provides in-memory file content to the scanner.
func WithWorkDir ¶
func WithWorkDir(path string) ScannerOption
WithWorkDir sets the working directory for the scanner.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
deps-walk
command
|
|
convert
module
|
|
convert-define
module
|
|
derivingbind
module
|
|
derivingjson
module
|
|
docgen
module
|
|
minigo
module
|
|
ffibridge
Package ffibridge provides helper types for the Foreign Function Interface (FFI) between the MiniGo interpreter and native Go code.
|
Package ffibridge provides helper types for the Foreign Function Interface (FFI) between the MiniGo interpreter and native Go code. |