goscan

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2025 License: MIT Imports: 17 Imported by: 10

README

go-scan

A lightweight Go type scanner that parses Go source files to extract information about types, constants, and functions without relying on go/packages or go/types. It works by directly parsing the AST (go/ast), making it fast and dependency-free for build-time tool generation.

This tool is designed for applications like OpenAPI document generation, ORM code generation, or any other task that requires static analysis of Go type definitions.

🚧 This library is currently under development.

Features

  • AST-based Parsing: Directly uses go/parser and go/ast for high performance.
  • Cross-Package Type Resolution: Lazily resolves type definitions across different packages within the same module.
  • Handles Recursive Types: Correctly resolves recursive type definitions (e.g., type Node struct { Next *Node }) and circular dependencies between packages without getting stuck in infinite loops.
  • Type Definition Extraction:
    • Parses struct definitions, including fields, tags, and embedded structs.
    • Handles complex types like pointers (*), slices ([]), and maps (map[K]V).
    • Recognizes type aliases (e.g., type UserID int) and their underlying types.
    • Parses function type declarations (e.g., type HandlerFunc func()).
  • Constant Extraction: Extracts top-level const declarations.
  • Function Signature Extraction: Extracts top-level function and method signatures.
  • Documentation Parsing: Captures GoDoc comments for types, fields, functions, and constants.
  • Package Locator: Finds the module root by locating go.mod and resolves internal package paths.
  • Symbol Definition Caching: (Experimental) Optionally caches the file location of scanned symbols (types, functions, constants) to speed up subsequent analyses by tools that need this information. The cache is stored as a JSON file.
  • External Type Overrides: Allows specifying how types from external (or even internal) packages should be interpreted by the scanner, e.g., treating uuid.UUID as a string.

Quick Start

Example Usage
package main

import (
	"context"
	"fmt"
	"log/slog"
	"os"

	"github.com/podhmo/go-scan"
	// If you are using the main package directly, import path might be different
	// For library usage, it's typically:
	// "github.com/podhmo/go-scan"
)

func main() {
	ctx := context.Background() // Or your application's context

	// Create a new scanner.
	// By default, it only scans packages within the current Go module.
	// To enable resolution of standard library and external packages from the module cache,
	// use the `WithGoModuleResolver` option.
	scanner, err := goscan.New(".", goscan.WithGoModuleResolver())
	if err != nil {
		slog.ErrorContext(ctx, "Failed to create scanner", slog.Any("error", err))
		os.Exit(1)
	}

	// --- Optional: Enable Symbol Cache ---
	// To enable symbol definition caching, set the CachePath.
	// If CachePath is an empty string (which is the default for a new Scanner), caching is disabled.
	// scanner.CachePath = filepath.Join(os.TempDir(), "my-app-symbol-cache.json") // Example
	// Or, for a user-level cache (ensure your app handles dir creation if needed by CachePath):
	// homeDir, _ := os.UserHomeDir()
	// if homeDir != "" {
	//    _ = os.MkdirAll(filepath.Join(homeDir, ".your-app-name"), 0750) // Ensure dir exists
	//    scanner.CachePath = filepath.Join(homeDir, ".your-app-name", "go-scan-symbols.json")
	// }

	// Important: Ensure to save the cache when your program exits if caching is enabled.
	// SaveSymbolCache will do nothing if scanner.CachePath is empty.
	defer func() {
		if err := scanner.SaveSymbolCache(); err != nil {
			slog.WarnContext(ctx, "Failed to save symbol cache", slog.Any("error", err))
		}
	}()
	// --- End Optional: Enable Symbol Cache ---

	// Scan a package by its import path
	// Replace with an actual import path from your project or testdata.
	// The example below uses testdata included in this repository.
	pkgImportPath := "github.com/podhmo/go-scan/testdata/multipkg/api"
	pkgInfo, err := scanner.ScanPackageByImport(pkgImportPath)
	if err != nil {
		slog.ErrorContext(ctx, "Failed to scan package", slog.String("package", pkgImportPath), slog.Any("error", err))
		os.Exit(1)
	}

	for _, t := range pkgInfo.Types {
		if t.Name == "Handler" {
			for _, f := range t.Struct.Fields {
				// Lazily resolve the type definition from another package
				def, err := f.Type.Resolve()
				if err != nil {
					slog.WarnContext(ctx, "Could not resolve field", slog.String("field", f.Name), slog.Any("error", err))
					continue
				}

				slog.InfoContext(ctx, "Field resolved", slog.String("field", f.Name), slog.String("resolved_type", def.Name))
				if def.Kind == goscan.StructKind { // goscan.StructKind is correct here as it's a re-exported constant
					slog.InfoContext(ctx, "Struct details", slog.String("type", def.Name), slog.Int("field_count", len(def.Struct.Fields)))
				}
			}
		}
	}

	// --- Optional: Using FindSymbolDefinitionLocation (often with cache) ---
	// This method attempts to find the file where a symbol is defined.
	// It uses the cache if enabled and will fallback to scanning if the symbol isn't found in cache
	// or if the cached entry is stale (e.g., file deleted).
	if pkgInfo.Types != nil && len(pkgInfo.Types) > 0 {
		firstType := pkgInfo.Types[0]
		symbolFullName := pkgImportPath + "." + firstType.Name

		filePath, err := scanner.FindSymbolDefinitionLocation(symbolFullName)
		if err != nil {
			slog.WarnContext(ctx, "Could not find definition location for symbol", slog.String("symbol", symbolFullName), slog.Any("error", err))
		} else {
			slog.InfoContext(ctx, "Definition of symbol found", slog.String("symbol", symbolFullName), slog.String("path", filePath))
		}
	}
}

Overriding External Type Resolution

In some scenarios, you may need to prevent the scanner from parsing a specific type from its source file. This is particularly useful for standard library types like time.Time, which can cause a mismatched package names error when a scan is triggered from a test binary (package main).

To handle this, you can provide a "synthetic" type definition to the scanner. The scanner will use this synthetic definition instead of attempting to parse the type's source code.

This is configured via the WithExternalTypeOverrides option, which accepts a map[string]*scanner.TypeInfo.

package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/podhmo/go-scan"
	"github.com/podhmo/go-scan/scanner" // For scanner.TypeInfo and scanner.ExternalTypeOverride
)

func main() {
	ctx := context.Background()

	// Define an override for "time.Time".
	// The key is the fully qualified type name.
	// The value is a pointer to a scanner.TypeInfo struct that describes the type.
	overrides := scanner.ExternalTypeOverride{
		"time.Time": &scanner.TypeInfo{
			Name:    "Time",
			PkgPath: "time",
			Kind:    scanner.StructKind, // It's a struct
		},
	}

	// Pass the overrides to the scanner during creation.
	s, err := goscan.New(
		".", // Start scanning from the current directory
		goscan.WithGoModuleResolver(),      // Still useful for other packages
		goscan.WithExternalTypeOverrides(overrides),
	)
	if err != nil {
		slog.ErrorContext(ctx, "Failed to create scanner", slog.Any("error", err))
		os.Exit(1)
	}

	// Now, when the scanner encounters a field of type `time.Time`, it will use the
	// synthetic TypeInfo provided above instead of trying to scan the "time" package.
	// The resulting scanner.FieldType will have its `IsResolvedByConfig` flag set to true,
	// and its `Definition` field will point to the synthetic `TypeInfo`.
}

When a type is resolved using an override:

  • A scanner.FieldType is created based on the provided scanner.TypeInfo.
  • The FieldType.IsResolvedByConfig flag will be set to true.
  • The FieldType.Definition field will point to the synthetic TypeInfo you provided.
  • Calling FieldType.Resolve() on such a type will immediately return the linked TypeInfo without performing a scan.

This feature gives you fine-grained control over how specific types are interpreted, which is essential for working around complex build contexts or for simplifying external types.

Caching Symbol Locations

The scanner can cache the file paths where symbols (types, functions, constants) are defined. This is useful for tools that repeatedly need to look up symbol locations.

  • Caching is enabled by setting the scanner.CachePath field to a non-empty string representing the desired path for the cache file.
  • If scanner.CachePath is an empty string (the default for a new Scanner instance), caching is disabled.
  • There is no default cache path if CachePath is left empty; it must be explicitly provided to enable caching.
  • Crucially, if caching is enabled (i.e., CachePath is set), you should call defer scanner.SaveSymbolCache() after creating your scanner instance. This ensures the cache is written to disk when your program finishes. SaveSymbolCache will do nothing if CachePath is empty.
  • The scanner.FindSymbolDefinitionLocation("package/import/path.SymbolName") method leverages this cache. If caching is enabled and a symbol is not found in the cache (or if the cached file path is no longer valid), it will attempt to scan the relevant package and update the cache. If caching is disabled, it will always perform a fresh scan.

This library is currently under development. See docs/todo.md for planned features.

More Examples

  • examples/derivingjson: Demonstrates generating JSON marshaling/unmarshaling methods, including support for oneOf (sum types).
  • examples/derivingbind: Shows how to generate methods for binding data from HTTP requests (query, path, header, body) to struct fields.
  • examples/minigo: A mini Go interpreter that uses go-scan for parsing and understanding Go code structure.
  • examples/convert: A prototype for generating type conversion functions between different Go structs. See examples/convert/README.md for details.
  • examples/deps-walk: A command-line tool to visualize package dependencies within a module. See examples/deps-walk/README.md for details.

Documentation

Index

Constants

View Source
const (
	StructKind    = scanner.StructKind
	AliasKind     = scanner.AliasKind
	FuncKind      = scanner.FuncKind
	InterfaceKind = scanner.InterfaceKind // Ensure InterfaceKind is available
)

Re-export scanner kinds for convenience.

View Source
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

func ResolvePath(ctx context.Context, path string) (string, error)

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`.

func WriteFile

func WriteFile(ctx context.Context, path string, data []byte, perm os.FileMode) error

WriteFile is a context-aware file writing function. It checks the context for a FileWriter and uses it if available. Otherwise, it falls back to os.WriteFile.

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

func (w *ModuleWalker) BuildReverseDependencyMap(ctx context.Context) (map[string][]string, error)

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

func (w *ModuleWalker) Walk(ctx context.Context, rootImportPath string, visitor Visitor) error

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

func (pd *PackageDirectory) SaveGoFile(ctx context.Context, gf GoFile, filename string) error

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

func (s *Scanner) BuildImportLookup(file *ast.File) map[string]string

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) Fset

func (s *Scanner) Fset() *token.FileSet

Fset returns the FileSet associated with the scanner.

func (*Scanner) ListExportedSymbols

func (s *Scanner) ListExportedSymbols(ctx context.Context, pkgPath string) ([]string, error)

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) Locator added in v0.0.2

func (s *Scanner) Locator() *locator.Locator

Locator returns the underlying locator instance.

func (*Scanner) LookupOverride

func (s *Scanner) LookupOverride(qualifiedName string) (*scanner.TypeInfo, bool)

LookupOverride checks if a fully qualified type name exists in the external type override map.

func (*Scanner) ModulePath

func (s *Scanner) ModulePath() string

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) RootDir

func (s *Scanner) RootDir() string

RootDir returns the module root directory from the scanner's locator.

func (*Scanner) SaveSymbolCache

func (s *Scanner) SaveSymbolCache(ctx context.Context) error

SaveSymbolCache saves the symbol cache to disk if CachePath is set.

func (*Scanner) Scan

func (s *Scanner) Scan(patterns ...string) ([]*Package, error)

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

func (s *Scanner) ScanFiles(ctx context.Context, filePaths []string) (*scanner.PackageInfo, error)

ScanFiles scans a specified set of Go files.

File paths in the `filePaths` argument can be provided in three forms:

  1. Absolute path (e.g., "/path/to/your/project/pkg/file.go").
  2. Path relative to the current working directory (CWD) (e.g., "pkg/file.go").
  3. 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

func (s *Scanner) ScanPackage(ctx context.Context, pkgPath string) (*scanner.PackageInfo, error)

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

func (s *Scanner) ScannerForSymgo() (*scanner.Scanner, error)

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

func (s *Scanner) UnscannedGoFiles(packagePathOrImportPath string) ([]string, error)

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:

  1. An absolute directory path to the package.
  2. A directory path relative to the current working directory (CWD).
  3. 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

type ScannerOption func(*Scanner) error

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.

type TypeInfo

type TypeInfo = scanner.TypeInfo

TypeInfo is an alias for scanner.TypeInfo.

type Visitor

type Visitor = scanner.Visitor

Visitor is an alias for scanner.Visitor.

Directories

Path Synopsis
examples
deps-walk command
convert 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.

Jump to

Keyboard shortcuts

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