Documentation
¶
Overview ¶
Package project discovers PHP files and analyses them in parallel.
Index ¶
- Constants
- Variables
- func AnalyzeBuffer(engine fixing.Analyzer, path string, src []byte, opt syntax.Options) diagnostic.FileResult
- func BuildFlowSnapshot(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ...) *flow.Snapshot
- func BuildIndex(files []string, opt syntax.Options, options infer.Options) *index.Index
- func BuildIndexCached(files []string, keep int, opt syntax.Options, options infer.Options, ...) (*index.Index, [][]byte)
- func BuildIndexKeep(files []string, keep int, opt syntax.Options, options infer.Options) (*index.Index, [][]byte)
- func BuildIndexUnread(ctx context.Context, files []string, opt syntax.Options, options infer.Options, ...) (*index.Index, []string)
- func CacheDir() string
- func ChangedInputs(ctx context.Context, s *Snapshot) ([]string, error)
- func ComposerWorld(root string, scope, indexed []string, skipped Skipped) index.World
- func ComposerWorldKey(root string) string
- func Discover(paths, exclude []string) ([]string, error)
- func DiscoverWith(paths, exclude, patterns []string) ([]string, error)
- func DiskProjectPaths(fallback string) func(path string) string
- func Each(ctx context.Context, n int, fn func(int)) error
- func ExtractSymbols(path string, src []byte, opt syntax.Options, options infer.Options) *index.FileSymbols
- func Fingerprint(b []byte) string
- func IndexSources(root string, files, paths, exclude []string) []string
- func ProjectPaths(exists func(name string) bool, fallback string) func(path string) string
- func ReadConfined(root *os.Root, name string, limit int64) ([]byte, error)
- func ReadSource(path string) ([]byte, error)
- func Run(e *analysis.Engine, files []string, opt syntax.Options) []diagnostic.FileResult
- func RunReport(e *analysis.Engine, files []string, srcs [][]byte, opt syntax.Options) []diagnostic.FileResult
- func RunSources(e *analysis.Engine, files []string, srcs [][]byte, opt syntax.Options) []diagnostic.FileResult
- func WithVendorFlow(root string, ix *index.Index, parse syntax.Options, options flow.Options) flow.Options
- func WorldInputs(root string) (composer, installed string)
- type FileStat
- type FlowBuild
- func BuildFlow(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ...) *FlowBuild
- func BuildFlowOrdered(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ...) *FlowBuild
- func BuildFlowRecorded(ctx context.Context, files []string, srcs [][]byte, opt syntax.Options, ...) *FlowBuild
- type FormatCache
- type FormatKey
- type FormatOptions
- type FormattedFile
- type Options
- type PreparedFix
- type Project
- type Skipped
- type Snapshot
- func AnalyzeSnapshot(ctx context.Context, s *Snapshot) (*Snapshot, error)
- func BuildSnapshot(ctx context.Context, root *os.Root, rules []analysis.Rule, paths []string, ...) (*Snapshot, error)
- func CaptureSnapshot(ctx context.Context, root *os.Root, rules []analysis.Rule, paths []string, ...) (*Snapshot, error)
- func OverlaySnapshot(ctx context.Context, s *Snapshot, name string, src []byte) (*Snapshot, error)
- type SymbolCache
- type VendorCache
Constants ¶
const ( MaxSnapshotBytes = 64 << 20 MaxSnapshotFiles = 10000 // VendorDigest is the Hashes key summarizing every vendor file hash. VendorDigest = "@vendor" )
Variables ¶
var ErrBaseline = errors.New("unreadable baseline")
ErrBaseline marks the error of a snapshot whose captured baseline does not decode.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DiskProjectPaths is ProjectPaths over the filesystem for absolute or working-directory-relative paths, falling back to fallback (made absolute).
func Each ¶
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 ¶
Fingerprint identifies exact bytes; it does not store supplied buffers.
func IndexSources ¶
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 ¶
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 ¶
ReadConfined never follows a link outside root or reads a special file.
func ReadSource ¶
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 ¶
WorldInputs returns the files ComposerWorld reads under root: composer.json, and the installed.json of the vendor directory it configures.
Types ¶
type FlowBuild ¶
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) FromDisk ¶
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 ¶
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 FormatCache ¶ added in v0.2.4
type FormatCache struct {
// contains filtered or unexported fields
}
FormatCache is the set of sources known to be formatted. A nil cache keeps nothing. It is safe for concurrent use.
func OpenFormatCache ¶ added in v0.2.4
func OpenFormatCache(dir, root string) *FormatCache
OpenFormatCache loads the format cache of the project at root from dir; nil when dir is "" or the running binary cannot be identified.
func (*FormatCache) Formatted ¶ added in v0.2.4
func (c *FormatCache) Formatted(key FormatKey) bool
Formatted reports whether the source of key is known to be formatted.
func (*FormatCache) Key ¶ added in v0.2.4
func (c *FormatCache) Key(settings string, src []byte) FormatKey
Key returns the key of formatting src with settings, a fingerprint of the resolved settings and target version.
func (*FormatCache) Save ¶ added in v0.2.4
func (c *FormatCache) Save() error
Save writes the entries of this run, then those of earlier runs it did not use, up to the bound; nothing when the run added none.
func (*FormatCache) Store ¶ added in v0.2.4
func (c *FormatCache) Store(key FormatKey)
Store records that the source of key is formatted.
type FormatOptions ¶ added in v0.2.4
type FormatOptions struct {
// Settings returns the settings of a file.
Settings func(path string) (*format.Resolved, error)
PHP phpversion.Version
// Cache skips the files known to be formatted; nil formats every one.
Cache *FormatCache
}
FormatOptions configure FormatFiles.
type FormattedFile ¶ added in v0.2.4
type FormattedFile struct {
Source []byte
Result format.Result
Perm os.FileMode
// Cached is set when the cache knew the file formatted.
Cached bool
// Err is set when the file could not be formatted; it wraps ErrSkipped
// for a file that is not regular (never formatted, as fix never fixes
// one).
Err error
}
FormattedFile is the outcome of formatting one file. Result.Output is the source when formatting changes nothing.
func FormatFiles ¶ added in v0.2.4
func FormatFiles(files []string, opt FormatOptions) []FormattedFile
FormatFiles formats every file with one worker per CPU. Outcomes are in input order; adapters own the writes.
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 ¶
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 ¶
Project binds discovered files to an explicit inspection set.
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 ¶
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 ¶
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 ¶
OverlaySnapshot replaces one file with supplied bytes and rebuilds semantic publication using captured sources only. Disk hashes remain the input 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 ¶
FlowOrderCache is OpenSymbolCache without reading the declarations, for FlowOrder and SaveFlowOrder alone: it caches no declaration.
func OpenSymbolCache ¶
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 ¶
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 ¶
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.
Source Files
¶
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. |