maven

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScopeCompile  = "compile"
	ScopeRuntime  = "runtime"
	ScopeTest     = "test"
	ScopeProvided = "provided"
	ScopeSystem   = "system"
	ScopeImport   = "import"

	// DefaultType is the default Maven artifact type.
	DefaultType = "jar"
)

Variables

View Source
var ErrNotFound = errors.New("resource not found in repository")

ErrNotFound is returned when a resource (POM, metadata) is definitively absent from a repository (HTTP 404). Maven Central is immutable, so a 404 almost never means the artifact was removed; it usually means the artifact lives in a different repository or the coordinate is wrong. Callers should treat it as a tolerable "not in this repo" signal rather than a hard failure, distinguishing it from transient/network errors (which are fatal once the HTTP agent's retries are exhausted).

Functions

func CanDecompose

func CanDecompose(dir string) bool

CanDecompose checks if a directory contains a Maven project.

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions compares two Maven version strings. Returns -1 if a < b, 0 if a == b, 1 if a > b.

func IsVersionRange

func IsVersionRange(s string) bool

IsVersionRange returns true if the string looks like a Maven version range.

func NormalizeLicense

func NormalizeLicense(lic License) string

NormalizeLicense maps a Maven POM license to its SPDX identifier using the shared license normalization package.

Types

type Build

type Build struct {
	Plugins          []Plugin          `xml:"plugins>plugin"`
	PluginManagement *PluginManagement `xml:"pluginManagement"`
}

Build represents the <build> section of a POM.

func (*Build) GetAllPlugins

func (b *Build) GetAllPlugins() []Plugin

GetAllPlugins returns all plugins from both <plugins> and <pluginManagement>, deduplicated by groupId:artifactId.

type Coordinate

type Coordinate struct {
	GroupID         string
	ArtifactID      string
	Version         string
	Classifier      string
	Type            string
	RepoURL         string // non-empty only when different from Maven Central
	SnapshotVersion string // resolved timestamped version for SNAPSHOTs (e.g. "1.0-20260418.130000-2")
}

Coordinate uniquely identifies a Maven artifact.

func (*Coordinate) ArtifactFilename

func (c *Coordinate) ArtifactFilename() string

ArtifactFilename returns the Maven artifact filename following the convention: {artifactId}-{version}[-{classifier}].{type} For SNAPSHOT artifacts with a resolved timestamped version, it uses the snapshot version (e.g. "1.0-20260418.130000-2") instead of "1.0-SNAPSHOT".

func (*Coordinate) Key

func (c *Coordinate) Key() string

Key returns "groupId:artifactId" for mediation lookups.

func (*Coordinate) PURL

func (c *Coordinate) PURL() string

PURL returns the Package URL for this coordinate, including qualifiers for type (if not jar), classifier (if set), and repository_url (if set).

func (*Coordinate) String

func (c *Coordinate) String() string

String returns "groupId:artifactId:version".

type Decomposer

type Decomposer struct{}

Decomposer extracts dependency data from Maven projects.

func New

func New() *Decomposer

New returns a new Maven decomposer.

func (*Decomposer) DefaultOptions

func (d *Decomposer) DefaultOptions() any

DefaultOptions returns the default options for the Maven decomposer.

func (*Decomposer) Extract

func (d *Decomposer) Extract(opts *api.DecomposerOptions) (*sbom.NodeList, error)

Extract parses the local pom.xml, resolves dependencies from Maven Central, and builds the complete dependency graph as a protobom NodeList.

func (*Decomposer) FindCodeBases

func (d *Decomposer) FindCodeBases(index *code.PathIndex) ([]string, error)

FindCodeBases locates directories containing pom.xml files.

func (*Decomposer) Requirements

func (d *Decomposer) Requirements(_ *api.DecomposerOptions) []api.Requirement

Requirements returns external tool requirements. The Maven decomposer requires no external binaries.

type Dependency

type Dependency struct {
	GroupID    string      `xml:"groupId"`
	ArtifactID string      `xml:"artifactId"`
	Version    string      `xml:"version"`
	Scope      string      `xml:"scope"`
	Type       string      `xml:"type"`
	Classifier string      `xml:"classifier"`
	Optional   string      `xml:"optional"`
	Exclusions []Exclusion `xml:"exclusions>exclusion"`
}

Dependency represents a Maven dependency declaration.

func (*Dependency) EffectiveScope

func (d *Dependency) EffectiveScope() string

EffectiveScope returns the dependency's scope, defaulting to "compile".

func (*Dependency) EffectiveType

func (d *Dependency) EffectiveType() string

EffectiveType returns the dependency's type, defaulting to "jar".

func (*Dependency) IsOptional

func (d *Dependency) IsOptional() bool

IsOptional returns true if the dependency is marked optional.

func (*Dependency) Key

func (d *Dependency) Key() string

Key returns "groupId:artifactId" used for mediation lookups.

type DependencyManagement

type DependencyManagement struct {
	Dependencies []Dependency `xml:"dependencies>dependency"`
}

DependencyManagement holds managed dependency versions and settings.

type DependencyTree

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

DependencyTree builds the resolved dependency graph from a Maven POM.

func NewDependencyTree

func NewDependencyTree(rootPOM *POM, resolver *Resolver, opts *Options) *DependencyTree

NewDependencyTree creates a new dependency tree builder.

func (*DependencyTree) AddBuildPlugins

func (dt *DependencyTree) AddBuildPlugins()

AddBuildPlugins adds build plugins from the POM as build dependencies of the root node. Plugins without a version are skipped (they're inherited from a parent but we can't resolve them without the version).

func (*DependencyTree) Build

func (dt *DependencyTree) Build() error

Build performs BFS dependency resolution and returns the resolved tree.

func (*DependencyTree) FetchHashes

func (dt *DependencyTree) FetchHashes(computeModern bool)

FetchHashes fetches artifact checksums for all resolved dependencies in parallel and stores them in the resolved dependency entries. When computeModern is true, it also downloads artifacts to compute SHA-256 and SHA-512 hashes locally.

func (*DependencyTree) ToNodeList

func (dt *DependencyTree) ToNodeList(opts *api.DecomposerOptions) (*sbom.NodeList, error)

ToNodeList converts the resolved dependency tree to a protobom NodeList.

type Exclusion

type Exclusion struct {
	GroupID    string `xml:"groupId"`
	ArtifactID string `xml:"artifactId"`
}

Exclusion represents a dependency exclusion.

func (*Exclusion) Matches

func (e *Exclusion) Matches(groupID, artifactID string) bool

Matches returns true if the exclusion matches the given coordinates. Supports wildcard "*" for both groupId and artifactId.

type License

type License struct {
	Name         string `xml:"name"`
	URL          string `xml:"url"`
	Distribution string `xml:"distribution"`
	Comments     string `xml:"comments"`
}

License represents a license declaration in a POM.

type Options

type Options struct {
	RepoURL         string // Maven repository URL (default: https://repo1.maven.org/maven2)
	Concurrency     int    // Number of parallel HTTP requests (default: 5)
	IncludeTest     bool   // Include test-scoped dependencies (default: false)
	IncludeProvided bool   // Include provided-scoped dependencies (default: false)
	IncludeOptional bool   // Include optional dependencies (default: false)
	IncludeBuild    bool   // Include build plugins as build dependencies (default: false)
}

Options configures the Maven dependency extraction.

type POM

type POM struct {
	XMLName              xml.Name              `xml:"project"`
	ModelVersion         string                `xml:"modelVersion"`
	Parent               *Parent               `xml:"parent"`
	GroupID              string                `xml:"groupId"`
	ArtifactID           string                `xml:"artifactId"`
	Version              string                `xml:"version"`
	Packaging            string                `xml:"packaging"`
	Name                 string                `xml:"name"`
	Description          string                `xml:"description"`
	URL                  string                `xml:"url"`
	Licenses             []License             `xml:"licenses>license"`
	Properties           Properties            `xml:"properties"`
	DependencyManagement *DependencyManagement `xml:"dependencyManagement"`
	Dependencies         []Dependency          `xml:"dependencies>dependency"`
	Build                *Build                `xml:"build"`
	Modules              []string              `xml:"modules>module"`
	Repositories         []Repository          `xml:"repositories>repository"`
}

POM represents a Maven POM file.

func InterpolatePOM

func InterpolatePOM(pom *POM) *POM

InterpolatePOM resolves all ${...} property placeholders in a POM. It modifies the POM in place and returns it for convenience.

func MergeParent

func MergeParent(child, parent *POM) *POM

MergeParent merges a parent POM into a child POM. Child values take precedence over parent values.

func ParsePomXML

func ParsePomXML(dir string) (*POM, error)

ParsePomXML reads and parses a pom.xml file from the given directory.

func ParsePomXMLData

func ParsePomXMLData(data []byte) (*POM, error)

ParsePomXMLData parses POM content from raw bytes. Handles non-UTF-8 encodings (e.g., ISO-8859-1) commonly found in Maven POMs.

func (*POM) EffectiveGroupID

func (p *POM) EffectiveGroupID() string

EffectiveGroupID returns the POM's groupId, falling back to parent's.

func (*POM) EffectiveVersion

func (p *POM) EffectiveVersion() string

EffectiveVersion returns the POM's version, falling back to parent's.

type Parent

type Parent struct {
	GroupID      string `xml:"groupId"`
	ArtifactID   string `xml:"artifactId"`
	Version      string `xml:"version"`
	RelativePath string `xml:"relativePath"`
}

Parent represents a POM parent reference.

type Plugin

type Plugin struct {
	GroupID      string       `xml:"groupId"`
	ArtifactID   string       `xml:"artifactId"`
	Version      string       `xml:"version"`
	Dependencies []Dependency `xml:"dependencies>dependency"`
}

Plugin represents a Maven build plugin.

func (*Plugin) EffectiveGroupID

func (p *Plugin) EffectiveGroupID() string

EffectiveGroupID returns the plugin's groupId, defaulting to "org.apache.maven.plugins" per Maven convention.

type PluginManagement

type PluginManagement struct {
	Plugins []Plugin `xml:"plugins>plugin"`
}

PluginManagement holds managed plugin versions.

type Properties

type Properties map[string]string

Properties is a map of Maven property key-value pairs. It requires custom XML unmarshaling because properties are arbitrary child elements: <jackson.version>2.15</jackson.version>

func (*Properties) UnmarshalXML

func (p *Properties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes Maven properties from XML.

type Repository

type Repository struct {
	ID        string            `xml:"id"`
	URL       string            `xml:"url"`
	Name      string            `xml:"name"`
	Snapshots *RepositoryPolicy `xml:"snapshots"`
	Releases  *RepositoryPolicy `xml:"releases"`
}

Repository represents a Maven repository declaration.

func (Repository) ReleasesEnabled

func (r Repository) ReleasesEnabled() bool

ReleasesEnabled returns true if this repository serves release artifacts. Maven defaults to true for releases.

func (Repository) SnapshotsEnabled

func (r Repository) SnapshotsEnabled() bool

SnapshotsEnabled returns true if this repository serves snapshot artifacts. Maven defaults to false for snapshots.

type RepositoryPolicy

type RepositoryPolicy struct {
	Enabled string `xml:"enabled"`
}

RepositoryPolicy controls whether a repository serves releases or snapshots.

type ResolvedDependency

type ResolvedDependency struct {
	Coordinate Coordinate
	Scope      string
	Optional   bool
	Licenses   []License
	Hashes     map[string]string // algo name -> hex digest (e.g. "SHA1" -> "abc123")
	Depth      int
}

ResolvedDependency represents a dependency after mediation.

type Resolver

type Resolver struct {
	Agent   *khttp.Agent
	RepoURL string
	// contains filtered or unexported fields
}

Resolver fetches and caches Maven POMs from remote repositories.

func NewResolver

func NewResolver(opts *Options) *Resolver

NewResolver creates a Resolver with the given options.

func (*Resolver) ComputeArtifactHashes

func (r *Resolver) ComputeArtifactHashes(coords []Coordinate) map[string]map[string]string

ComputeArtifactHashes downloads artifacts in parallel and computes SHA-256 and SHA-512 digests locally. It returns a map keyed by "groupId:artifactId:version" containing algo->hex digest maps.

func (*Resolver) FetchAllArtifactHashes

func (r *Resolver) FetchAllArtifactHashes(coords []Coordinate) map[string]map[string]string

FetchAllArtifactHashes fetches SHA-1 and SHA-256 checksums for multiple artifacts in parallel using the Agent's GetGroup. It returns a map keyed by "groupId:artifactId:version" containing algo->digest maps.

func (*Resolver) FetchAvailableVersions

func (r *Resolver) FetchAvailableVersions(groupID, artifactID string) ([]string, error)

FetchAvailableVersions fetches maven-metadata.xml and returns all versions.

func (*Resolver) FetchPOM

func (r *Resolver) FetchPOM(groupID, artifactID, version string) (*POM, error)

FetchPOM fetches a POM from the resolver's configured repository.

func (*Resolver) FetchPOMFrom

func (r *Resolver) FetchPOMFrom(groupID, artifactID, version, repoURL string) (*POM, error)

FetchPOMFrom fetches a POM from an explicit repository URL, falling back to the resolver's configured RepoURL when repoURL is empty.

func (*Resolver) ResolveEffectivePOM

func (r *Resolver) ResolveEffectivePOM(pom *POM) (*POM, error)

ResolveEffectivePOM resolves the full parent chain, merges inherited data, processes BOM imports, and interpolates all properties.

func (*Resolver) ResolveSnapshotVersion

func (r *Resolver) ResolveSnapshotVersion(groupID, artifactID, version, ext, classifier string) string

ResolveSnapshotVersion resolves a SNAPSHOT version against the resolver's configured repository. See ResolveSnapshotVersionFrom for details.

func (*Resolver) ResolveSnapshotVersionFrom

func (r *Resolver) ResolveSnapshotVersionFrom(groupID, artifactID, version, ext, classifier, repoURL string) string

ResolveSnapshotVersionFrom fetches the version-level maven-metadata.xml for a SNAPSHOT version from an explicit repository URL (or the resolver's default when empty) and returns the resolved timestamped version string (e.g. "1.0-20260418.130000-2") for the given extension and classifier. Returns the original version unchanged if the metadata cannot be fetched.

func (*Resolver) ResolveVersionRange

func (r *Resolver) ResolveVersionRange(groupID, artifactID, rangeSpec string) (string, error)

ResolveVersionRange resolves a version range to a concrete version.

type VersionRange

type VersionRange struct {
	LowerBound     string
	UpperBound     string
	LowerInclusive bool
	UpperInclusive bool
}

VersionRange represents a Maven version range constraint.

func ParseVersionRange

func ParseVersionRange(s string) (*VersionRange, error)

ParseVersionRange parses a Maven version range string. Supported formats: [1.0,2.0), [1.0], (,1.0], [1.0,), etc.

func (*VersionRange) Contains

func (vr *VersionRange) Contains(version string) bool

Contains returns true if the given version satisfies this range.

func (*VersionRange) SelectVersion

func (vr *VersionRange) SelectVersion(candidates []string) string

SelectVersion picks the highest version from candidates that satisfies the range.

Jump to

Keyboard shortcuts

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