nixpkgs’ maven package is built from Apache
Maven’s binary release tarball. This is because
building Maven requires Maven1 which leads to a chicken and egg
problem. And the same is the case for most of its dependencies and its
build-time tooling, which are Maven-built projects too. After seeing how easy
it is to bootstrap Apache Ant from
source, I was up for a challenge
and wanted to find out whether building Maven from source without having Maven
is possible afterall.
nix-maven-bootstrap is the
result. It reconstructs the dependency graph of
apache/maven bottom-up as Nix derivations
and reassembles it into a complete Maven distribution: all 51 jars compiled
from source by a generic javac + jar builder, no Maven anywhere in the
build, and a working mvn that can build Maven itself from Maven’s own POM
build descriptions. This post is the story of how it was built.
Why build Maven without Maven?
A source build is worth the work for the same reasons Nix prefers to build
anything from source. Every class in every jar the distribution ships traces
back to a source tree that can be read and audited; nothing relies on
trusting Apache’s build farm, and no fixed-output derivation full of
downloaded jars sits in the graph. When a CVE lands in a bundled library,
the fix is a patch and a rebuild instead of waiting for a new upstream
tarball. nixpkgs tracks meta.sourceProvenance precisely so consumers can
tell compiled bytecode from fetched bytecode, and the maven that builds
everyone else’s Java code is itself fetched bytecode.
Getting there is its own problem. The POMs are the starting point: they
define the dependency graph, the code-generation steps, the resource
filtering, and the packaging metadata. What we can’t do is execute them,
because executing a POM build requires Maven itself. It turns out we don’t
have to. Compiling Java is just javac plus jar, and everything else the
POMs ask Maven to do can be re-expressed as Nix derivations and setup hooks.
That was the whole idea. To keep the scope manageable I decided on the
following ground rules:
- Build Maven without requiring Maven.
- Build everything that ends up in the distribution from source.
- Build everything that participates at build time and contributes code from source.
- Allow compile-time-only dependencies to be fetched as binaries from Maven Central.
The rest of this post is those rules applied to Maven’s real dependency graph, in the order I built them.
The first jar
The concrete meaning of “build Maven from source” comes from Maven’s release distribution tarball: it ships 51 jars, and every one of them needs a derivation. I started at the bottom of the graph, with the package nothing in the Plexus and Maven worlds can go without: plexus-utils, a utility library with no dependencies of its own.
The
first version
was a plain stdenvNoCC.mkDerivation: find the sources under
src/main/java, run javac, pack the classes with jar, install the result
to $out/share/java, plus a second javac pass for each multi-release level
above 8. Pared down to the essentials:
stdenvNoCC.mkDerivation (finalAttrs: {
pname = "plexus-utils";
version = "3.6.4";
src = fetchFromGitHub { owner = "codehaus-plexus"; /* ... */ };
nativeBuildInputs = [ jdk ];
buildPhase = ''
find src/main/java -name '*.java' > build/sources.txt
javac --release 8 -encoding UTF-8 -d build/classes @build/sources.txt
# one extra pass per multi-release level (9, 10, 11), into
# build/classes/META-INF/versions
'';
installPhase = ''
mkdir -p $out/share/java
jar --create --file $out/share/java/plexus-utils.jar \
--manifest build/MANIFEST.MF -C build/classes .
'';
})
The second package was maven-model, the first module of Maven’s own reactor (Maven’s name for the multi-module build that produces all of Maven’s jars), and it raised the two problems that every remaining jar would raise:
- maven-model compiles against plexus-utils, so the package I created before becomes a build input, and its jar has to land on javac’s classpath.
- Part of the build logic lives outside javac, in Maven’s build
descriptions: POMs wire in Maven plugins that generate sources, filter
resources, and write package metadata, and none of those plugins can run
without a functional Maven. maven-model’s case is
Modello, which generates
most of its pom-handling classes from
.mdomodels at build time.
Both solutions became conventions for the whole graph. The classpath
question is settled by one convention: jars install to $out/share/java,
and a dependency contributes $out/share/java/* to javac’s classpath. In
the builder, that convention is two lines (simplified):
classpath = lib.concatMapStringsSep ":"
(dep: "${dep}/share/java/*") compileClasspath;
classpathArgs = lib.optionalString
(compileClasspath != [ ]) ''-classpath "${classpath}"'';
Every declared dependency is mapped to its jar path, and the joined result
becomes the -classpath argument passed to javac.
For the code-generation problem, after exploring the Modello repository I found
out it had a Java main class, so it could be called just like an ordinary Java
program. Furthermore I realized I could use setup
hooks to do what
Maven plugins do in upstream builds. Running Modello became the first setup
hook: an ordinary Nix package whose setup-hook.sh registers in a stdenv phase
hook, activated by putting it in nativeBuildInputs. The Maven distribution
does not ship Modello itself, but the code it generates, so by the ground
rules Modello is built from source too, along with its own Maven-built
dependencies (plexus-utils 4 among them), none of which ship either.
Two packages in, the pattern was obvious. Every jar left in the graph needs
the same things: sources compiled, dependencies on the classpath, and the
occasional extra step before or after. I moved on and
extracted
buildJavaPackage
from those two concrete packages, instead of designing it up front.
The builder knows how to compile Java and pack a jar, and nothing else.
maven-model’s module definition now reads like this. The src inherit and the
surrounding project derivation plumbing are left out; that is the next
section’s topic:
maven-model = buildJavaPackage {
pname = "maven-model";
# version and src are inherited from the shared Apache Maven checkout
subdir = "maven-model";
nativeBuildInputs = [
modello
maven-pom-hook
];
mavenGroupId = "org.apache.maven";
meta.license = lib.licenses.asl20;
compileDependencies = [ plexus-utils ];
manifest."Automatic-Module-Name" = "org.apache.maven.v3.model";
# what Modello generates, and from which model
modelloModels = [ "maven-model/src/main/mdo/maven.mdo" ];
modelloTypes = [
"java"
"xpp3-reader"
"xpp3-extended-reader"
"xpp3-writer"
"xpp3-extended-writer"
];
modelloVersion = "4.0.0";
};
The maven-pom-hook in that listing is a hook package as well: it writes the
pom metadata into the jar, the way Maven’s jar plugin does. The manifest
attribute started out as a single automaticModuleName option, until I
realized jar manifest entries are a more general concept the builder should be
able to configure, and an attribute set is exactly the right shape for writing
a MANIFEST.MF file. Maven’s transitive resolution gets flattened by hand:
when a module’s pom declares a dependency that itself has compile dependencies,
those become explicit list entries. Declaring what you use is arguably the more
correct model anyway, which is why compileDependencies behaves like Gradle’s
implementation
scope: a library states what it compiles against, and consumers don’t inherit
it transitively. It’s tedious and mechanical, and javac tells you when you
missed one. The cases javac can’t catch are the runtime-only dependencies, and
those mean reading the pom.
Walking the reactor
With the builder in place, the work became walking Maven’s reactor in
dependency order: maven-artifact, maven-builder-support, maven-settings,
maven-repository-metadata, maven-plugin-api, and up. Most modules were one
more call to buildJavaPackage. Whenever that didn’t produce the same
result as the upstream build, I knew that some logic in the upstream build
needed to be ported to the Nix machinery.
The first such place was the reactor itself. Multi-module reactors are
modeled as one
project derivation per
repository,
with the module jars under passthru.modules. Because the project
derivation is built with finalAttrs, modules can cross-reference jars of
the same project:
passthru.modules = {
maven-model = buildJavaPackage { … };
maven-plugin-api = buildJavaPackage {
# …
compileDependencies = [
plexus-utils
finalAttrs.passthru.modules.maven-model
finalAttrs.passthru.modules.maven-artifact
];
};
};
All modules build from the same checkout: apache/maven is one git repository
that produces all fourteen jars, and since fetchFromGitHub is
content-addressed, every module unpacks the same store path. Maven’s reactor
is replaced by the Nix dependency graph.
The second place was dependencies that had no derivations yet. maven-plugin-api
needs Sisu,
classworlds, the
launcher’s class loader framework, and half of Plexus, and none of those
existed when it came up in the walk. Its first
version
compiled against binary jars fetched from Maven Central with nixpkgs’
fetchMavenArtifact fetcher, to be replaced once those packages were built
for real. fetchMavenArtifact is really just a workaround for optional and
provided dependencies: it fetches single artifacts without resolving their
transitive dependencies, so funnelling what it fetches into
buildJavaPackage as a regular dependency would produce an incomplete
runtime classpath.
I invented the fourth ground rule, allowing compile-time-only binary dependencies, primarily because of one of Sisu’s modules: it carries a lot of optional and provided dependencies, among them JUnit 4 and JUnit Framework (the JUnit Jupiter API). Building JUnit Framework from source would have opened a new can of worms, because it contains Kotlin code: that would have meant building Kotlin from source as well, or using nixpkgs’ Gradle build support to run JUnit Framework’s upstream Gradle build and produce the jars that way. Several modules had such a first version; replacing the stand-ins became its own pass once the walk reached the end.
The biggest single addition came from how Maven finds its components. Maven’s
component discovery runs through a Sisu index. The index is an XML file that
is produced by running an annotation processor. It happens at build time
inside a Maven plugin. As a result the builder has annotation processing built
in: annotationProcessors names the processor entrypoints and
annotationProcessorDependencies puts their jars on javac’s -processorpath
only, off the compile classpath and out of the runtime closure. Without the
index, a jar’s annotated components are invisible to Maven: its container runs
in index mode, reads only META-INF/sisu/javax.inject.Named and the legacy
META-INF/plexus/components.xml, and never falls back to classpath scanning,
so the distribution fails the first time something needs one of those
components. This is what a package definition with annotation processing
wired in looks like (trimmed):
buildJavaPackage {
pname = "plexus-cipher";
version = "2.0";
src = fetchFromGitHub {
owner = "codehaus-plexus";
repo = "plexus-cipher";
tag = "plexus-cipher-2.0";
hash = "sha256-UamirLHchgpHcV/5N2edb9rf10TUHSCIRBYkUHW70QU=";
};
mavenGroupId = "org.codehaus.plexus";
compileDependencies = [
javax-inject
sisu.passthru.modules.sisu-inject
];
annotationProcessors = [ "org.eclipse.sisu.space.SisuIndexAPT6" ];
annotationProcessorDependencies = [ sisu.passthru.modules.sisu-inject ];
}
The Sisu index has one exception in the graph: maven-compat. The module exists
to keep Maven’s pre-Guice internals alive for old plugins, and its components
predate javax.inject: they carry Plexus’s own @Component annotation, which
the Sisu processor does not index, so the annotation processor produces no
index for the module at all. Upstream’s maven-compat jar therefore ships the
legacy META-INF/plexus/components.xml as its descriptor, 34 components, the
only module in the distribution that uses the format. The module compiles fine
without the file; it fails at runtime, when an old plugin looks a legacy
component up and gets a Guice binding error (maven-javadoc-plugin 3.1.1 and
maven-surefire-plugin 2.22.2 were the cases that came up when I added smoke
tests I’ll talk about in a bit). Producing the file the upstream way was
circular: plexus-component-metadata:generate-metadata is a Maven mojo, so
unlike Modello it has no standalone main class to call, and its dependency
closure includes maven-plugin-api, maven-model, and maven-core. The generator
depends on the tool being bootstrapped. I decided to implement a CLI myself.
plexus-metadata-generator
builds the metadata engine from the plexus-containers sources the graph already
fetches for plexus-component-annotations, plus a small Main class that boots
the Plexus container and calls the generator through it. A setup hook
runs the tool over a module’s compiled classes in postBuild and writes the
descriptor into the jar. The tool pins two more binary dependencies, jdom2 and
qdox, compile-time-only under the fourth ground rule and staying out of the
distribution: it is build-time tooling, like Modello. The descriptor it
generates is byte-identical to upstream’s, which the distribution comparison in
the next section asserts.
I implemented annotation processing inside the builder instead of a setup hook,
because it is a feature of javac. Everything else tool-shaped stays outside, as
ordinary Nix packages containing a setup-hook.sh that registers in a stdenv
phase hook. A package activates one by putting it in nativeBuildInputs,
exactly like makeWrapper and the rest of the stdenv machinery:
| Hook | Runs | Purpose |
|---|---|---|
modello | preBuild | Generates Java sources from Modello .mdo models, e.g. maven-model’s pom classes |
maven-pom-hook | postBuild | Writes META-INF/maven/…/pom.properties and copies the module pom into the jar, like maven-jar-plugin does |
filter-resources-hook | postBuild | Substitutes ${placeholder} tokens in filtered resources |
plexus-metadata-generator | postBuild | Generates META-INF/plexus/components.xml from Plexus @Component annotations on the compiled classes, like plexus-component-metadata:generate-metadata does for upstream jars (maven-compat’s) |
The filter-resources hook is another one of those ports: Maven filters
resources by substituting ${...} tokens, and maven-core’s
build.properties, the file the mvn launcher reads for its version
banner, is produced that way. Without the hook, mvn -version prints
null for the version.
The rest of the walk produced smaller additions, each from a concrete
module: support for source layouts that don’t match Maven’s default
directories, reproducible jar metadata, and an aggregate runtime classpath
that later assembles the distribution’s lib/.
The last big addition showed up as a wrong result instead of a build failure.
With only compile and runtime lists, everything a module compiled against also
propagated into its runtime closure, so Maven’s provided scope had no
equivalent: jars Sisu compiles against but doesn’t need at runtime leaked into
the assembled lib/, adding a second Guice jar (guice-servlet, next to the
Guice Sisu actually runs on), a second SLF4J jar, and the JUnit family.
compileOnlyDependencies closes that gap, by putting jars only on javac’s
compile classpath but not adding them to the runtime closure.
buildJavaPackage therefore provides three attributes that line up with
Maven’s scopes like this:
| Attribute | On javac’s classpath | In the runtime closure | Maven analogue |
|---|---|---|---|
compileDependencies | yes | yes | compile scope |
runtimeDependencies | no | yes | runtime scope |
compileOnlyDependencies | yes | no | provided / optional |
The rest of the graph, and the distribution, and the self-build
The reactor walk had left binary stand-ins behind wherever a module needed a
library that had no derivation yet. The second pass replaced them: the
third-party graph, built from source and worked through bottom-up, the same
way. I sorted this work into three tiers. API-only jars (annotations and
interfaces such as javax.inject, servlet-api, osgi-core, cdi-api,
aopalliance, jspecify, error-prone-annotations) compile against the JDK
alone. Plain single-module libraries like commons-cli, gson, guava,
httpclient, and asm with only few dependencies follow the same pattern with
more code. The last tier is the multi-module reactors, one repository producing
many jars: Maven itself with 14 modules, Maven
Resolver with 9, Sisu, Wagon, SLF4J, and
Modello. Most of these projects build themselves with Maven, which is why they
are all built with buildJavaPackage instead of their own build tooling.
With every dependency source-built, the distribution
assembly
is mostly linking and copying, and the result has the same shape as the
official binary distribution: launcher scripts, configuration, classworlds in
boot/2, and exactly the 50 jars upstream’s lib/ carries.3 Most of the
non-jar resources files I could copy verbatim from the source repository.
At this point assembling the distribution was the easy part. Checking that the
result matches what Maven’s own build produces took more work: the flake’s
passthru.tests.distribution-compare test downloads and unpacks the upstream
binary tarball and pins the file inventory, jar sets by artifactId, license
files, the DI descriptors each jar carries (Sisu index and components.xml,
byte-compared where both sides ship them), and the bin/, conf/, and
lib/ext/ listings included. Writing the descriptor check caught two drifts
in wagon’s hand-written descriptor: Unix line endings where upstream’s
generated file uses CRLF, and an ASF license header the release file doesn’t
carry. I ran a deeper comparison as a one-off during development: all 51 jar pairs,
compared entry by entry, class files and resources alike. All 14 Maven reactor modules and all
9 resolver modules match upstream exactly in class sets. The remaining
differences are build-tooling artifacts that don’t change behavior: 13 jars
miss a JPMS module-info.class that upstream’s tooling generates and the git
sources don’t contain, the empty synthetic classes javac 8-era builds emitted
(55 in guava alone) are gone because modern javac doesn’t generate
them,4 and the manifests differ in build metadata (Build-By: Nix).
In the end, I decided not to encode the deeper comparison because I was afraid
it would break with every upcoming Maven release.
The last piece is self-hosting. The distribution builds Maven from Maven’s own POM build descriptions:
$ nix run .#maven.passthru.self-build
This clones apache/maven at the maven-3.10.2 tag, runs the full reactor
build with the source-built mvn (plugins and dependencies fetched from
Maven Central), and assembles a distribution whose launcher banner reports
the same version and commit as the upstream release. That is my definition
of done for a bootstrap: the tool you built can build itself.
The distribution is meant as a drop-in replacement for nixpkgs’ maven, and
that is a claim about code that lives in nixpkgs. So in addition to self-build,
I added tests that build real nixpkgs derivation using
maven.buildMavenPackage but substitute maven with the source-built one as
passthru.tests.smoke-<name>:
small consumers like cfr and zxing whole, the offline mvn run included, heavy
ones like h2 and checkstyle at their fetchedMavenDeps fetch, the
maven-sensitive part. A consumer’s dependency fetch is a fixed-output
derivation whose hash is nixpkgs’ pinned mvnHash, so passing means the
source-built maven resolved the exact artifact graph nixpkgs pinned.
A drop-in replacement for nixpkgs’ maven
The flake exposes an overlay that makes the source-built distribution
nixpkgs’ maven. Using it is the standard overlay wiring, through the
nixpkgs.overlays option of a NixOS configuration:
{
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
inputs.nix-maven-bootstrap.url = "github:britter/nix-maven-bootstrap";
outputs = { self, nixpkgs, nix-maven-bootstrap }: {
nixosConfigurations.my-host = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
({ ... }: {
nixpkgs.overlays = [ nix-maven-bootstrap.overlays.default ];
})
];
};
};
}
The NixOS wiki’s overlays page covers
the other ways to apply an overlay: standalone Nix code, shell.nix, or Home
Manager.
The overlay keeps nixpkgs’ contract for what a maven package is: the
distribution lives under $out/maven, the path consumers like IntelliJ address
directly, and $out/bin/mvn defaults JAVA_HOME to a bundled jdk_headless
that can be overridden at eval time and at runtime. nixpkgs’ own builder
factory (mkBuildMavenPackage, the one maven_4 already reuses) passes
through, and the buildMavenPackage it produces is bound to the source-built
maven, so everything from the nixpkgs manual’s Maven
section works unchanged:
maven.buildMavenPackage, mvnHash, overrideMavenAttrs, buildOffline,
manualMvnArtifacts.
Drop-in consumers inherit some deviations as stated earlier: 13 jars miss
their module-info.class; the jars carry checked-in module poms instead of
upstream’s release-installed ones; the
Apache remote-resources bundle
(META-INF/DEPENDENCIES, LICENSE, NOTICE) is absent, though every
third-party jar ships its license text next to it; and the bytecode floor
sits at or above upstream’s everywhere (ASM and Guava build at
--release 11). Two sources have compromises of origin:
servlet-api
2.5 has no git source anymore, so it compiles the
JSR-154 expert group’s sources jar
from Central, and
osgi-core’s
eight bnd projects get re-laid-out into a
standard Maven tree during fetch. None of
this affects mvn runs; it matters if you embed the distribution’s jars as
libraries. And no fetched bytecode ships: meta.sourceProvenance stays empty
because every jar in the distribution was compiled here.
What I learned, and what’s next
On the Nix side, the big realization was that while there are very
sophisticated build tools, producing libraries or simple command line
applications doesn’t need a lot of machinery. Nix can be used as a Java build
tool directly, without going through another build tool: mkDerivation and
setup hooks provide the extensibility that is needed. The rest reuses
what stdenv already has: nixpkgs-style pkgs/by-name auto-discovery
over a small makeScope makes a new package a new directory with no wiring
edits, and the fixed-point reactor pattern cross-references modules without
a single rec.
On the Java side, this project was archaeology. Building Maven’s graph by
hand teaches you how Maven actually works: why the boot jar is special, how
Sisu indexes components and where the legacy Plexus descriptor takes over,
how Modello generates the classes behind Maven’s
pom.xml and settings.xml parsing from .mdo models at build time, and how
much of a Java “build” is really resource filtering and packaging metadata.
The README lists the questions I haven’t decided on: running package tests (a test-classpath aggregation plus JUnit built from source), making the JDK configurable, whether the custom dependency attributes should map onto stdenv’s input attributes, and building bnd for a more faithful osgi-core. Furthermore after sharing this with more people I’d like to explore how feasible it is to get this upstream into nixpkgs.
If you want to poke at the result:
$ nix build github:britter/nix-maven-bootstrap#maven
If you need help packaging Java applications with Nix, or with NixOS in general, I offer NixOS consulting services. Feel free to get in touch with me!
Footnotes
-
If you’re looking for a way to build Java code using Maven in Nix, nixpkgs provides the
maven.buildMavenPackagebuilder: the project’s dependencies are resolved once into a fixed-output derivation, and the build runs offline against it. I’ve written about how that works before. Those builders all need a working Maven, which is why they don’t help with building Maven itself. ↩ -
classworlds is the launcher’s class loader framework. The boot jar stays out of
lib/so the container can’t load its own classes a second time through the application realm. ↩ -
The lib set is Maven’s reactor runtime closure (47 jars, classworlds included) minus classworlds, plus the four transport jars the distribution pom wires for maven-compat’s Wagon lookup and that no reactor module depends on:
wagon-file,wagon-http,wagon-http-shared(whichwagon-httppulls in), andmaven-resolver-transport-wagon. 47 − 1 + 4 = 50. ↩ -
javac 8-era builds emitted these empty synthetic classes when compiling code with type-use annotations such as
@Nullable; modern javac doesn’t generate them. They are empty and unused, so the jars behave identically. ↩

Benedikt Ritter
Gradle & NixOS Consultant
Developer productivity consultant with five years at Gradle Inc. building Develocity, and co-founder of TestLens. Apache Software Foundation member and founder of GradleX. I help engineering teams ship faster through better Gradle build tooling and reproducible NixOS infrastructure.