project

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package project discovers PHP files and analyses them in parallel.

Index

Constants

View Source
const (
	MaxSnapshotBytes = 64 << 20
	MaxSnapshotFiles = 10000
	// VendorDigest is the Hashes key summarizing every vendor file hash.
	VendorDigest = "@vendor"
)

Variables

View Source
var ErrBaseline = errors.New("unreadable baseline")

ErrBaseline marks the error of a snapshot whose captured baseline does not decode.

View Source
var ErrSkipped = errors.New("not a regular file")

ErrSkipped marks files fix leaves alone without failing.

Functions

func AnalyzeBuffer

func AnalyzeBuffer(engine fixing.Analyzer, path string, src []byte, opt syntax.Options) diagnostic.FileResult

AnalyzeBuffer analyzes supplied bytes without reading the filesystem.

func BuildFlowSnapshot

func BuildFlowSnapshot(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ix *index.Index, options flow.Options) *flow.Snapshot

BuildFlowSnapshot builds project-local summaries without including vendor bodies. Parsing is bounded by the same source reader as ordinary analysis. Trees are retained only during bounded composition, then released. Once ctx is done the build stops between files and rounds, and the snapshot is incomplete: callers check ctx before using it.

func BuildIndex

func BuildIndex(files []string, opt syntax.Options, options infer.Options) *index.Index

BuildIndex parses files in parallel and returns their symbols layered over the embedded stubs. Files are added in input order (Discover sorts paths), so when a symbol is declared more than once (polyfills) the same declaration wins on every run.

func BuildIndexCached

func BuildIndexCached(files []string, keep int, opt syntax.Options, options infer.Options, cache *SymbolCache) (*index.Index, [][]byte)

BuildIndexCached is BuildIndexKeep that takes the declarations of the files past keep from cache while they are unchanged, records the others in it, and saves it.

func BuildIndexKeep

func BuildIndexKeep(files []string, keep int, opt syntax.Options, options infer.Options) (*index.Index, [][]byte)

BuildIndexKeep is BuildIndex that also returns the sources it read for the first keep files (nil where unreadable), so a following Run over them does not read them again (IndexSources lists the analyzed files first).

func BuildIndexUnread

func BuildIndexUnread(ctx context.Context, files []string, opt syntax.Options, options infer.Options, cache *SymbolCache) (*index.Index, []string)

BuildIndexUnread is BuildIndexCached keeping no source and also returning the files whose declarations it could not read (unreadable, too large or crashing the extraction). Once ctx is done, files not started yet are left out: the index is then incomplete, and the caller drops it.

func CacheDir

func CacheDir() string

CacheDir is where adapters keep declarations between runs: $CUSTOS_CACHE_DIR, else custos under the user cache directory; "" when neither is known.

func ChangedInputs

func ChangedInputs(ctx context.Context, s *Snapshot) ([]string, error)

ChangedInputs reports inputs that differ from the snapshot manifest. A file whose size and modification time are unchanged is trusted unless it was modified within racyWindow of the capture; every other file is hashed.

func ComposerWorld

func ComposerWorld(root string, scope, indexed []string, skipped Skipped) index.World

ComposerWorld derives what the index knows of the project's world (see index.World) from Composer's metadata under root. scope lists the project directories whose PHP files are indexed, indexed the files of the index and skipped what the walks and the indexing left out (paths absolute or relative to the working directory).

func ComposerWorldKey

func ComposerWorldKey(root string) string

ComposerWorldKey summarizes the part of root's composer.json that ComposerWorld reads (autoload, requirements, suggestions, vendor directory): two files with the same key give the same world. An unreadable file gives "", one that is not JSON its whole text.

func Discover

func Discover(paths, exclude []string) ([]string, error)

Discover lists *.php files under paths, skipping excluded directory names or relative paths, hidden directories (see hidden), declaration files (see declarationOnly), and symlinks that do not lead to a regular file inside the scanned path.

func DiscoverWith

func DiscoverWith(paths, exclude, patterns []string) ([]string, error)

DiscoverWith is Discover that also lists files whose base name matches one of patterns (path.Match syntax, e.g. "composer.json"), as requested by rules implementing analysis.FilePatternRule (see Engine.FilePatterns).

func DiskProjectPaths

func DiskProjectPaths(fallback string) func(path string) string

DiskProjectPaths is ProjectPaths over the filesystem for absolute or working-directory-relative paths, falling back to fallback (made absolute).

func Each

func Each(ctx context.Context, n int, fn func(int)) error

Each runs fn(i) for every i below n on one worker per CPU. Only the dispatcher observes cancellation, between items. A panic in fn fails the call (the first one is returned as an error) instead of the process; the other items still run.

func ExtractSymbols

func ExtractSymbols(path string, src []byte, opt syntax.Options, options infer.Options) *index.FileSymbols

ExtractSymbols parses one file and returns its symbols, with the return types of untyped functions and methods inferred from their bodies (infer.AnnotateReturns). Before adding the result to a project index, call DropStaleInferred on it once the project symbols are known.

func Fingerprint

func Fingerprint(b []byte) string

Fingerprint identifies exact bytes; it does not store supplied buffers.

func IndexSources

func IndexSources(root string, files, paths, exclude []string) []string

IndexSources returns files to index: the analyzed files first, then the other PHP files under the project paths, then those of the project's vendor directory (symbols only; neither is analyzed). Discovery applies exclude everywhere; vendor also leaves out test directories and the custos package. Each file appears once, so a project path that holds vendor adds nothing twice.

func ProjectPaths

func ProjectPaths(exists func(name string) bool, fallback string) func(path string) string

ProjectPaths returns analysis.Config.ProjectPath: a file path relative to its project root, with forward slashes. The root is the nearest ancestor directory holding custos.json, else the outermost one holding composer.json (a package or fixture application nested in a project stays part of it), else fallback. A file outside its root keeps its path. exists reports whether a file exists; it is asked once per directory.

func ReadConfined

func ReadConfined(root *os.Root, name string, limit int64) ([]byte, error)

ReadConfined never follows a link outside root or reads a special file.

func ReadSource

func ReadSource(path string) ([]byte, error)

ReadSource reads a source file, but never more than syntax.MaxFileSize+1 bytes: a larger (hostile or sparse) file yields a prefix that syntax.Parse then reports as too large, instead of being loaded whole into memory. Only regular files are read (a symlink to a device or FIFO fails instead of blocking). Callers must not write the result back as the file content.

func Run

func Run(e *analysis.Engine, files []string, opt syntax.Options) []diagnostic.FileResult

Run parses and analyses files with one worker per CPU. Results are returned in input order.

func RunReport

func RunReport(e *analysis.Engine, files []string, srcs [][]byte, opt syntax.Options) []diagnostic.FileResult

RunReport is RunSources for reporting only: each finding keeps its fix titles (so it still reads as fixable) but not the edit closures, which hold the file's syntax tree and semantic data alive until the end of the run (gigabytes on large legacy trees with many findings).

func RunSources

func RunSources(e *analysis.Engine, files []string, srcs [][]byte, opt syntax.Options) []diagnostic.FileResult

RunSources is Run with sources already read (srcs[i] for files[i]; a nil or missing entry is read from disk), e.g. by BuildIndexKeep.

func WithVendorFlow

func WithVendorFlow(root string, ix *index.Index, parse syntax.Options, options flow.Options) flow.Options

WithVendorFlow returns options whose snapshots answer the contracts of dependency callables by summarizing, on demand, the files under the vendor directory of root that declare them.

func WorldInputs

func WorldInputs(root string) (composer, installed string)

WorldInputs returns the files ComposerWorld reads under root: composer.json, and the installed.json of the vendor directory it configures.

Types

type FileStat

type FileStat struct {
	Size    int64
	ModTime int64
}

FileStat is the cheap identity of an input between two hash checks.

type FlowBuild

type FlowBuild struct {
	Snapshot *flow.Snapshot
	// contains filtered or unexported fields
}

FlowBuild is a flow snapshot with the summaries of each file it was composed from, so that Update redoes only what an edit invalidates.

func BuildFlow

func BuildFlow(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ix *index.Index, options flow.Options) *FlowBuild

BuildFlow is BuildFlowSnapshot keeping what Update needs.

func BuildFlowOrdered

func BuildFlowOrdered(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ix *index.Index, options flow.Options, order map[string]int) *FlowBuild

BuildFlowOrdered is BuildFlow summarizing each file, the first time, after the files whose contracts it read in an earlier build: order gives their depth by path (see Order), and a path it lacks has depth 0. Files are summarized in waves of growing depth, the deepest together, each wave against the snapshot of the waves before; composition then goes on as in BuildFlow. Most files thus read settled contracts the first time instead of being summarized again once they settle. Cold builds discover the dependency order during composition; the supplied order is only a hint that can avoid early repeated summaries.

func BuildFlowRecorded

func BuildFlowRecorded(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ix *index.Index, options flow.Options, order map[string]int) *FlowBuild

BuildFlowRecorded is BuildFlowOrdered keeping every summary it makes, so that Update, when an edit within a recursion makes it summarize files from none again, takes those the files' contracts still support instead of summarizing them (see reuse). The language server, which updates the build on every pause in editing, takes it; it costs memory a single run does not spend.

func (*FlowBuild) Files

func (b *FlowBuild) Files() []string

Files returns the files the build summarized, in build order.

func (*FlowBuild) FromDisk

func (b *FlowBuild) FromDisk(path string) bool

FromDisk reports whether the build summarized path as read from disk: it is one of its files and no source was supplied for it.

func (*FlowBuild) Order

func (b *FlowBuild) Order() map[string]int

Order returns, by path, the depth of each file in the relation of the contracts its summaries read: 0 for a file reading none of another file, else one more than the deepest file it reads, ignoring the reads that close a cycle. BuildFlowOrdered takes it for a later build.

func (*FlowBuild) Update

func (b *FlowBuild) Update(ctx context.Context, changed map[string][]byte, ix *index.Index) (*FlowBuild, bool)

Update returns the build for the same files after the sources of the changed ones (path → source, now supplied) changed, without changing any declaration other files see: the project index is the one the build used. The changed files are summarized again first; then, as in BuildFlow, every file whose summaries read a contract that changed, from its supplied source or else from disk. Files are parsed only when summarized again. ok is false when a changed path is not one of the build's files, or when ctx is done before the update completes (what it summarized is then dropped).

type Options

type Options struct {
	Root           string
	Paths, Exclude []string
	// Scope lists the project paths whose PHP files are indexed for symbols
	// besides the analyzed ones, so cross-file facts do not depend on which
	// files a run names. Empty means Paths.
	Scope []string
	// Cache is the directory keeping, between runs, the declarations of
	// files indexed but not analyzed (see SymbolCache) and the flow
	// summaries of the analyzed ones (see flowSteps); empty disables it.
	Cache string
	// FlowOrder summarizes the flow of the analyzed files in the order the
	// last run with the cache saved, and saves this run's (see
	// BuildFlowOrdered). A call chain composing without an order gives up
	// on may then settle, so results may differ from a run without it.
	FlowOrder bool
	// ParseOnce keeps the syntax tree of each analyzed file from indexing
	// until its analysis, so it is parsed once instead of once per phase
	// and per flow summary: faster, but every analyzed file's tree stays in
	// memory until the analysis reaches it.
	ParseOnce bool
	// RecordedKey identifies the baseline the engine's checks see (see
	// analysis.Engine.WithRecorded): the findings cache is kept for an
	// engine that sees one only when it is set.
	RecordedKey string
	Analysis    analysis.Config
	Parse       syntax.Options
}

Options contains resolved configuration; adapters own flags and settings.

type PreparedFix

type PreparedFix struct {
	Source, Output []byte
	Perm           os.FileMode
	Applied        int
	Err            error
}

PreparedFix is the result of fixing one file; out is nil when nothing changed.

func PrepareFixes

func PrepareFixes(engine *analysis.Engine, files []string, sources [][]byte, parse syntax.Options) []PreparedFix

PrepareFixes fixes every file with one worker per CPU (files are independent; the engine is safe for concurrent use). sources holds bytes already read for the first files (nil where unread); the rest are read here. Outcomes are in input order so diffs and messages stay deterministic.

type Project

type Project struct {
	Engine  *analysis.Engine
	Files   []string
	Options Options
}

Project binds discovered files to an explicit inspection set.

func Open

func Open(rules []analysis.Rule, opt Options) (*Project, error)

Open configures inspections and discovers their requested file patterns.

func (*Project) AnalyzeReport

func (p *Project) AnalyzeReport() []diagnostic.FileResult

AnalyzeReport indexes project and vendor declarations, reuses read sources, and releases lazy edit closures after analysis. Results retain input order.

func (*Project) PrepareFixes

func (p *Project) PrepareFixes() []PreparedFix

PrepareFixes computes changes without writing; the adapter owns writes.

type Skipped

type Skipped struct {
	Dirs, Files []string
}

Skipped records what a walk for the index left out below the paths it scanned, spelled as the walk spells paths: the directories it did not enter and the files Composer may load (see loadable) it did not index.

func IndexSourcesSkipping

func IndexSourcesSkipping(root string, files, paths, exclude []string) ([]string, Skipped)

IndexSourcesSkipping is IndexSources also returning what the walks left out (see Skipped): a path they could not walk counts as a skipped directory, the vendor directory never does for the project walk (the vendor walk covers it).

type Snapshot

type Snapshot struct {
	Engine  *analysis.Engine
	Index   *index.Index
	Sources map[string][]byte
	// Hashes is the manifest of retained inputs plus one VendorDigest entry.
	Hashes map[string]string
	// VendorHashes and Stats describe individual files for change detection.
	VendorHashes map[string]string
	Stats        map[string]FileStat
	Files        []string
	OwnFiles     []string
	Vendor       []string
	// Skipped lists the first vendor entries left out of semantic indexing
	// (symlinks, oversized or unparsable files); SkippedCount counts them all.
	Skipped      []string
	SkippedCount int
	Symbols      []*index.FileSymbols
	Results      []diagnostic.FileResult
	Config       *config.Config
	// Baseline is the captured baseline's key in Sources, "" without one.
	Baseline string
	// Recorded is that baseline once analyzed (see AnalyzeSnapshot), its
	// entries naming files relative to its directory; nil without one.
	Recorded *baseline.Baseline
	// Paths are the requested inputs; empty selects the configured paths.
	Paths    []string
	Captured time.Time
	// contains filtered or unexported fields
}

Snapshot is immutable after construction. Its input manifest covers every configuration and semantic source read. Project inputs are retained in Sources; vendor files contribute declarations and a hash only.

func AnalyzeSnapshot

func AnalyzeSnapshot(ctx context.Context, s *Snapshot) (*Snapshot, error)

AnalyzeSnapshot publishes index and flow copies before producing findings.

func BuildSnapshot

func BuildSnapshot(ctx context.Context, root *os.Root, rules []analysis.Rule, paths []string, cache *VendorCache) (*Snapshot, error)

BuildSnapshot constructs cancellable, root-confined project evidence.

func CaptureSnapshot

func CaptureSnapshot(ctx context.Context, root *os.Root, rules []analysis.Rule, paths []string, cache *VendorCache) (*Snapshot, error)

CaptureSnapshot captures bounded inputs without parsing or analyzing PHP.

func OverlaySnapshot

func OverlaySnapshot(ctx context.Context, s *Snapshot, name string, src []byte) (*Snapshot, error)

OverlaySnapshot replaces one file with supplied bytes and rebuilds semantic publication using captured sources only. Disk hashes remain the input manifest.

func (*Snapshot) Source

func (s *Snapshot) Source(name string) ([]byte, error)

Source returns the captured bytes of a project input, or re-reads a vendor file and checks it against the manifest.

type SymbolCache

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

SymbolCache keeps, between runs, the declarations of the files a run indexes without analyzing them (vendor and the rest of the project paths), so a run over a few files does not parse every dependency again.

An entry is trusted while its file keeps its size and modification time; a file modified within racyWindow of the run is never stored, as it may change again without either moving. The cache key covers the custos binary and the parse and inference options, so a rebuild or another PHP version starts afresh. Entries hold declarations as extracted, before the index drops inferred returns that depend on project functions (see DropStaleInferred). A nil *SymbolCache caches nothing.

func FlowOrderCache

func FlowOrderCache(dir, root string, opt syntax.Options, options infer.Options) *SymbolCache

FlowOrderCache is OpenSymbolCache without reading the declarations, for FlowOrder and SaveFlowOrder alone: it caches no declaration.

func OpenSymbolCache

func OpenSymbolCache(dir, root string, opt syntax.Options, options infer.Options) *SymbolCache

OpenSymbolCache loads the cache of the project at root from dir. A missing, unreadable or outdated cache file starts empty; nil is returned when the running binary cannot be identified.

func (*SymbolCache) FlowOrder

func (c *SymbolCache) FlowOrder(files []string, options flow.Options) map[string]int

FlowOrder returns, by path as files name them, the order the last flow build of these files with options saved; nil when there is none.

func (*SymbolCache) Save

func (c *SymbolCache) Save() error

Save writes the entries this run used, unless they are the ones it read. Files no longer indexed drop out. The declarations of analyzed files this run did not read are carried over: a run over a few files, or the language server's, which analyzes none, must not drop the entries of a run over the whole project.

func (*SymbolCache) SaveFlowOrder

func (c *SymbolCache) SaveFlowOrder(order map[string]int, options flow.Options) error

SaveFlowOrder keeps order (by path, see FlowBuild.Order) for the next build with options, unless it is the one FlowOrder read.

type VendorCache

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

VendorCache carries vendor hashes and declarations between snapshots of one root, so an unchanged dependency is neither read nor parsed again. It is not safe for concurrent snapshots.

Directories

Path Synopsis
Package baseline records known findings so that only new ones are reported.
Package baseline records known findings so that only new ones are reported.
Package config loads custos.json and derives defaults from composer.json.
Package config loads custos.json and derives defaults from composer.json.

Jump to

Keyboard shortcuts

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