detectorkit

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package detectorkit provides shared helper functions for detector implementations: manifest metadata inference, source-position wiring, remediation hint assembly, subgraph partitioning, and build-tool readiness and timeout helpers.

Index

Constants

View Source
const BuildToolTimeout = 10 * time.Minute

BuildToolTimeout bounds a single build-tool invocation (mvn, gradle, sbt). These commands resolve dependency graphs over the network, and a stalled remote (observed twice with Maven Central) would otherwise hang the scan indefinitely because the pipeline context carries no deadline. The bound is deliberately generous — healthy resolutions finish in seconds to a few minutes even on cold caches — so hitting it means the tool is stuck, not slow.

Variables

This section is empty.

Functions

func AppendPosition

func AppendPosition(out map[string][]*sdk.SourcePosition, key string, pos *sdk.SourcePosition)

AppendPosition appends pos under key unless the same file/line/column position was already recorded.

func AttachPositionCandidates

func AttachPositionCandidates(g *sdk.Graph, positions map[string][]*sdk.SourcePosition, keys func(*sdk.DependencyNode) []string)

AttachPositionCandidates populates PackageLocation.Position on graph nodes using one or more lookup keys per dependency. It preserves multiple declaration sites and skips exact duplicate file/line/column entries.

func AttachPositions

func AttachPositions(g *sdk.Graph, positions map[string]*sdk.SourcePosition, nameKey func(*sdk.DependencyNode) string)

AttachPositions populates PackageLocation.Position on graph nodes whose normalized key (derived by nameKey) appears in the positions map. Nodes already carrying a Location with the same RealPath are left untouched.

nameKey returns the lookup key for a graph node. Detectors typically derive it from dep.Name, dep.Org+":"+dep.Name, or a language-specific normalization. Returning "" skips the node.

func BuildRemediationHints

func BuildRemediationHints(
	request sdk.RemediationHintRequest,
	manager sdk.PackageManager,
	actions []sdk.RemediationAction,
	advice RemediationAdvice,
) sdk.RemediationHintResponse

BuildRemediationHints assembles occurrence-scoped hints from a detector's graph. It handles only common graph traversal; the calling detector owns its advertised actions and manager-specific advice.

func BuildToolContext

func BuildToolContext(ctx context.Context) (context.Context, context.CancelFunc)

BuildToolContext derives a context for one build-tool invocation, bounded by BuildToolTimeout on top of whatever deadline ctx already carries.

func CommandNotReadyError

func CommandNotReadyError(name string, err error) error

CommandNotReadyError returns a compact readiness error for a missing tool, or nil when err is nil.

func EnsureNode added in v0.9.0

func EnsureNode[T sdk.GraphNode](g *sdk.Graph, node T) (T, error)

EnsureNode inserts a node into a graph, or returns the node already carrying its identity.

Every detector needs this: a lockfile can name one package more than once, and a graph keeps one node per identity. Doing the existence check by hand is what left a dozen detectors silently discarding a duplicate record's data -- each copy of the check written independently, each deciding differently what to do with the loser.

The fold itself is Graph.InsertNode's: scopes, locations, and origins union onto the survivor. This adds the typed return and the nil tolerance callers rely on, so a detector inserting a module gets a module back without asserting. A survivor of a different kind is an error rather than a silent nil: two nodes sharing one ID across kinds means the ID grammars collided, and a detector must not carry on with a node that is not what it built.

func InferManifestMetadata

func InferManifestMetadata(req sdk.DetectionRequest, evidencePatterns []string) sdk.ManifestMetadata

InferManifestMetadata determines the manifest metadata for detectors that naturally resolve one graph.

func JavaReady

func JavaReady(ctx context.Context, logger *zap.Logger) error

JavaReady verifies that a Java runtime is available for JVM build tools. It returns nil when a runtime is usable and a non-nil error describing the reason otherwise. The probe is bound to ctx and additionally guarded by an internal timeout so a hung `java` cannot stall a scan.

func PromoteToModule added in v0.9.0

func PromoteToModule(g *sdk.Graph, nodeID, manifestPath string) (string, error)

PromoteToModule replaces a node with a module node declared by a manifest path, keeping its edges, and returns the surviving node's ID.

A node's kind and identity are both fixed at construction, so a detector that only learns ownership later cannot set a flag or rewrite an ID afterwards. Maven learns which graph roots are reactor modules after parsing the dependency tree, and which directory declares each one later still; Cargo learns a member's directory only once the metadata's absolute manifest paths can be made relative to the scan. Both replace the node, and this is the one place that knows how: build the module, re-point every edge, remove the old node.

It is idempotent for the path it is given: a module already declared by that manifest is returned unchanged, and one declared by another manifest is re-minted, because the declaring path is part of a module's identity.

Edges are re-added by ID, so callers must not hold node pointers across the call; the returned ID is what to hold instead.

func PropagateScopes added in v0.9.0

func PropagateScopes(g *sdk.Graph, rootID string, seed func(*sdk.DependencyNode) sdk.Scope)

PropagateScopes seeds the scopes of a root's direct dependencies and spreads them breadth-first through the graph, so a package reachable on a runtime path is marked runtime even when it is also a development dependency. Any dependency node still unscoped afterwards defaults to runtime: a package the resolver installed is used at runtime unless something said otherwise.

This lived three times over in one detector family, with the same termination trap in each copy -- a walk that revisits a node whose scope did not change never finishes on a cyclic graph. Only the seed differed, so that is the parameter: seed reports where a direct dependency starts, and a nil seed reads the node's own primary scope. Non-dependency nodes are skipped; scope is a claim about a consumed package, and a manifest or a module does not carry one.

A root that is not in the graph is a no-op: nothing is seeded, nothing propagates, and the runtime default is not applied either. A root that is present but has no direct dependencies is not that case -- the default still runs, because the resolver installed whatever is there.

func RequestWorkingDir

func RequestWorkingDir(req sdk.DetectionRequest) string

RequestWorkingDir returns the directory a detector should operate in for the given request, preferring the explicit project path and falling back to the subproject execution target location.

func ScanLines

func ScanLines(path string, fn func(line int, text string)) error

ScanLines invokes fn for every line in the file at path. The callback receives the 1-based line number and the raw line text (without the trailing newline). Returns the underlying scanner error if any. Returns nil silently when the file does not exist — detector position wiring is best-effort.

func SubgraphFrom

func SubgraphFrom(g *sdk.Graph, rootID string) (*sdk.Graph, error)

SubgraphFrom returns a new graph containing rootID and every node and edge reachable from it in g. Detectors that resolve a whole workspace/reactor into one graph use it to partition the merged graph into per-module manifest entries: each module entry carries the module root plus its reachable dependency subtree. Node pointers are shared with the source graph, matching how detectors already share nodes across container entries.

Types

type RemediationAdvice

type RemediationAdvice func(
	action sdk.RemediationAction,
	name, version, manifestPath string,
) string

RemediationAdvice builds manager-specific, read-only guidance for a strategy. Concrete detectors own this function and the wording it returns.

Jump to

Keyboard shortcuts

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