Repository navigation
[MNG-8650] mvnval, a tool to validate POMs without building them - #13276
Conversation
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Core-extension loading and incorrect invalid-format exit handling leave documented behavior and safety requirements unresolved.
Review effort: Lite
Findings: 1
Open (3)
What changed in this PR
Adds mvnval, a raw POM validation CLI with text/JSON reporting, API support, launchers, documentation, and tests.
Changes:
- Adds raw model building and validation problem collection.
- Adds CLI parsing, reporting, exit codes, and distribution integration.
- Adds unit/integration tests and threat-model documentation.
Review notes: core extensions may still load during bootstrap, invalid --format returns exit code 1 instead of 2, and the public path API documentation does not match returned values.
| File | Reviewed changes |
|---|---|
THREAT_MODEL.md |
Documents mvnval input handling. |
its/core-it-suite/src/test/resources/mvnval-validate-pom/duplicate-dependency/pom.xml |
Invalid duplicate-dependency fixture. |
its/core-it-suite/src/test/resources/mvnval-validate-pom/clean/pom.xml |
Clean validation fixture. |
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh10442MvnvalValidatePomTest.java |
Adds CLI integration tests. |
its/core-it-suite/pom.xml |
Enables executable permissions for tests. |
impl/maven-impl/src/test/java/org/apache/maven/impl/model/RawModelReadingTest.java |
Tests raw model behavior. |
impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultModelBuilder.java |
Implements raw model building. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/ValidateInvokerTest.java |
Tests validation invocation. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/TestUtils.java |
Provides CLI test utilities. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/ReportTest.java |
Tests report behavior. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/ReporterTest.java |
Tests report rendering. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/OutputFormatTest.java |
Tests output format selection. |
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnval/CommonsCliValidateOptionsTest.java |
Tests option parsing. |
impl/maven-cli/src/main/java/org/apache/maven/cling/MavenValCling.java |
Adds the CLI entry point. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/ValidateParser.java |
Parses validation arguments. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/ValidateInvoker.java |
Executes validation and determines exit codes. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/ValidateContext.java |
Provides validation context. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/TextReporter.java |
Implements text reporting. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/Reporter.java |
Defines reporting abstraction. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/Report.java |
Models validation results. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/package-info.java |
Documents the implementation package. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/OutputFormat.java |
Defines output formats. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/JsonReporter.java |
Implements JSON reporting. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnval/CommonsCliValidateOptions.java |
Defines validation options. |
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/CommonsCliOptions.java |
Registers --val. |
api/maven-api-core/src/main/java/org/apache/maven/api/services/ModelBuilder.java |
Adds the raw-build API. |
api/maven-api-cli/src/site/markdown/index.md |
Documents the new tool. |
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/Tools.java |
Registers tool metadata. |
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/ParserRequest.java |
Adds parser requests. |
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/mvnval/ValidateOptions.java |
Defines public validation options. |
api/maven-api-cli/src/main/java/org/apache/maven/api/cli/mvnval/package-info.java |
Documents the validation API package. |
apache-maven/src/assembly/maven/bin/mvnval.cmd |
Adds the Windows mvnval launcher. |
apache-maven/src/assembly/maven/bin/mvnval |
Adds the Unix mvnval launcher. |
apache-maven/src/assembly/maven/bin/mvn.cmd |
Adds Windows dispatch support. |
apache-maven/src/assembly/maven/bin/mvn |
Adds Unix dispatch support. |
apache-maven/src/assembly/component.xml |
Includes the new scripts in distributions. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
elharo
left a comment
There was a problem hiding this comment.
Where will this be documented? In which files/URLs specifically? If they're in this repo, they must be part of this PR. If they're in maven-site there should be a concurrent PR with those changes too.
gnodet-bot
left a comment
There was a problem hiding this comment.
New feature — mvnval POM validation tool
Well-structured addition. The core extension isolation, exit code contract, and reactor-aware validation are all carefully designed and well-tested. A few observations:
Regarding existing reviews:
- Copilot's core extension concern — already addressed:
ValidateInvoker.createCoreExtensionSelector()returns an empty list, the THREAT_MODEL entry documents this, andExtensionTests.shouldLoadNoCoreExtensiontests it. - Copilot's exit code 2 concern — already addressed:
CommonsCliValidateOptions.parse()deliberately does not check--format(see its Javadoc), andValidateInvoker.execute()catchesIllegalArgumentExceptionfromOutputFormat.parse()and returnsBAD_OPERATION(exit 2).ValidateInvokerTest.shouldRejectUnknownFormatWithBadOperation()confirms this. - elharo's
httpvshttpslicense URLs — all license headers in the project usehttp://www.apache.org/licenses/LICENSE-2.0. This is a project-wide convention, not a PR issue. - elharo's
mvnval.cmdline 24 comment —MAVEN_BATCH_ECHOaccepting'on'matchesmvnenc.cmd,mvnup.cmd, and the mainmvn.cmd. Not a regression.
Refactoring quality: The loadReactor extraction from buildBuildPom is clean — buildBuildPom() now calls loadReactor(true, true) preserving original behavior, while buildRaw() calls loadReactor(false, false) for the relaxed validation context. The reportReactorLoadFailures flag correctly scopes error suppression to reactor scanning only; the actual POM validation path remains unaffected.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
In this repo the only file documenting the tool set is Past that I couldn't find a page for |
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 9ba8305..6781eef — all previous findings addressed
Previous findings status:
-
✅
reportReactorLoadFailurespropagation (gnodet-bot) — Addressed.derive()now copies the flag to child sessions. Correct fix. -
✅
determineWritercomment (gnodet-bot) — Addressed. Comment reworded to accurately describe whydetermineWriteris used instead ofcontext.writer. -
✅ Core extension loading (Copilot, gnodet-bot) — Addressed and improved. The previous approach (override
createCoreExtensionSelector()to return empty list) only blocked extensions. The new approach (no-op overrides ofcontainer(),postContainer(),lookup(),init(),settings()) is strictly more thorough — it prevents the entire DI container from bootstrapping, which also blocks.mvn/extensions.xml,maven.ext.class.path, and.mvn/settings.xml. The THREAT_MODEL entry was updated accordingly. -
✅ Exit code 2 for invalid format (Copilot) — Addressed. The
validate()override now remaps the base class's exit code 1 (parse failure) toBAD_OPERATION(2), so a bad--formatvalue or any other parse error exits 2 instead of colliding with the "POM rejected" exit code. -
✅ Exit code contract — Now clean: 0=OK, 1=ERROR, 2=BAD_OPERATION, 3=CANCELED, 4=WARNINGS. The WARNINGS shift from 3→4 to accommodate CANCELED is correct and consistent with mvnenc/mvnup.
New changes assessment:
- The Ctrl+C handling (
Terminal.Signal.INT→ thread interrupt → check between POMs → CANCELED exit) is correct.Thread.interrupted()clears the flag where it's acted on. - The broad
catch (Exception e)inexecute()prevents unexpected failures from becoming exit code 2 (which the handleException base would produce). Both mvnenc and mvnup do the same. - The
UserInterruptExceptioncatch handles JLine-level interrupts separately from signal-level ones. Correct. - Test coverage for the new behavior is adequate:
shouldStandUpNoContainer,shouldTurnParseFailureIntoBadOperation, mock terminal setup inTestUtils.
Solid follow-up commits. No new issues.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
There was a problem hiding this comment.
Thanks for this — the use case is clearly stated and the implementation is clean. I have a few concerns about the API addition before this goes in.
buildRaw encodes a limitation that belongs to the caller, not the API
The new ModelBuilderSession.buildRaw() is essentially "run the model builder pipeline but collect problems instead of throwing on the first validation error". That's a useful and legitimate contract. But the name encodes how far the pipeline runs (raw = file + raw model phase only) as if that were fixed by the method, when it's already controlled by RequestType on the ModelBuilderRequest.
I'd suggest renaming it to validate:
/**
* Validates the model described by the request, collecting all problems
* without throwing on validation errors. The request's {@link ModelBuilderRequest.RequestType}
* controls how far the pipeline runs. Only throws when the model cannot be read at all.
*
* @since 4.1.0
*/
default ModelBuilderResult validate(ModelBuilderRequest request) throws ModelBuilderException {
...
}Same implementation for now — the raw case stays as-is. But the name doesn't bake in the limitation, and we don't need a second API addition later when someone wants effective-model validation.
Effective-model validation is already achievable — without any new API
The PR description notes that validation stops at the raw model, and that a dependency whose version comes from the parent's dependencyManagement is only caught in validateEffectiveModel. That's true today, but it doesn't require any new API to fix. ApiRunner.createSession(injectorConsumer, localRepo) already accepts a local repository path, so mvnval could expose:
--depth raw|effective(defaulting toeffective) to control how far the pipeline runs-Dmaven.repo.local/--local-repository <path>for an explicit local repository (defaulting to~/.m2/repositoryas usual)--temp-local-repositoryto use a throwaway directory deleted on exit — useful for CI gates that want full isolation
With --depth effective, the full validateEffectiveModel runs — catching things like missing dependency versions inherited from a parent's dependencyManagement. No custom ModelResolver needed, no new API, just wiring what's already there.
The clearRequestScopedCache in buildRaw is a code smell
The finally block in buildRaw explicitly clears the request-scoped cache because the method knows it shouldn't share session state with a concurrent build() call on the same ModelBuilderSession. But the right answer isn't special-casing the cleanup: it's using a fresh ModelBuilderSession per validation job, which is what createSession() is for. A validate() method that documents "use a dedicated session" doesn't need this workaround — the cache lifecycle is just the session lifetime.
Reuse a single ModelBuilderSession across all validated POMs
The current implementation creates a fresh session per POM (modelBuilder.newSession() inside the loop). A shared parent is therefore re-resolved once per child — for a multi-module project with mvnval **/*.pom, that's N resolutions of the same parent. With a single ModelBuilderSession for the whole batch (the reactor pattern), parent POMs are resolved once and cached. The shell handles glob expansion; the tool already accepts multiple path arguments; sharing the session is the only missing piece for efficient multi-POM validation.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 6781eef..addbec6 — all maintainer feedback addressed
Previous findings status:
-
✅ Rename
buildRaw→validate(gnodet) — Addressed in adf8539. The API method now names the contract, not the pipeline stage. Javadoc rewritten accordingly, adding session isolation guidance ("give a validation run a session of its own"). -
✅
clearRequestScopedCachecode smell (gnodet) — Addressed in 6f09770. The workaround is gone —validate()now usessessionFor()(the same factorybuild()uses), so session lifetime governs the cache. No special cleanup needed. -
✅ Reuse single
ModelBuilderSessionacross all validated POMs (gnodet) — Addressed in 6f09770.ValidateInvoker.validateAll()creates oneModelBuilderSessionviabuilder.newSession()and passes it to everyvalidateOne()call. New testshouldValidateSeveralProjectsOnOneSessionexercises two independent reactors on the same session. -
✅ Lazy StringBuilder in
quote()(rmannibucau) — Addressed in addbec6. Theescaped(char)method is extracted, andquote()now returns'"' + value + '"'without allocating a StringBuilder when nothing needs escaping.
Solid follow-up. No new issues.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
elharo
left a comment
There was a problem hiding this comment.
Is it OK to use https instead of http in LICENSE and source headers?
Yes. When the LICENSE text was last updated in 2004, https did not have the widespread adoption it does now. It is acceptable, in fact encouraged, to use https wherever http is currently used in LICENSE files as well as in individual source headers.
|
I agree https would be better, and I can't use it here. Spotless checks every Java Under CI that's |
|
Two things I'd like you to decide. Should And can The rest is in, adf8539 and 6f09770. Renamed, cache clear gone, one session for Two things I got wrong. Sharing a session doesn't trip Same numbers with a session per POM, because every |
|
Thanks for addressing the rename, the cache cleanup, and the shared session — those are all improvements. On the network question: I think the default should be For the local repository, the default should be
|
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits addbec6..5b080ab — substantial new functionality, all previous findings addressed, solid implementation
Previous findings status:
- ✅
buildRaw→validate(gnodet) — Addressed in earlier commits. The API method is named for its contract. - ✅
clearRequestScopedCachecode smell (gnodet) — Gone. - ✅ Reuse single
ModelBuilderSession(gnodet) — Addressed in 6f09770, then intentionally reverted to a session per POM in the new commits. The revert is justified: derived sessions sharemappedSources, so when two POMs from different reactors declare the samegroupId:artifactId(e.g. as a parent), the first POM's mapping answers the second POM's parent lookup, making the verdict depend on argument order. TestshouldNotDependOnArgumentOrderexercises this regression. Creating a fresh session per POM costs nothing — each pass walks the reactor from the root anyway. - ✅ Effective model validation (gnodet) — Addressed in f75cdab. Default is
--mode effective, with--mode rawas opt-out. The naming differs from gnodet's original suggestion (--depth raw|effective) but the semantics match exactly. - ✅ Lazy StringBuilder in
quote()(rmannibucau) — Addressed in earlier commit. - ✅ elharo's documentation question — Answered in PR comments.
New changes assessment (addbec6..5b080ab):
-
ValidationModetwo-pass design is correct.EFFECTIVErunsvalidate()(raw) first, thenbuild(BUILD_EFFECTIVE)on the sameModelBuilderSession. This works becausesessionFor()derives a newModelBuilderSessionStatefor the second request, and the builder caches file/raw models per source — so raw-phase problems aren't duplicated. The early-exit on raw errors avoids pointless network access. -
validate()API contract relaxation is intentional and well-designed. The interface now says "must not resolve from a remote repository" while the implementation Javadoc (onDefaultModelBuilder) documents the specific guarantee: "stops after the raw model". This leaves room for future implementations to run further without violating the interface contract, while callers rely on the problems, not on model accessors whose@Nonnullcontracts don't hold here. -
Refused options (
-o,-s,-ps,-is) in effective mode are correct. Resolution runs on the sessionApiRunnerbuilds, which reads the user'ssettings.xmland cannot be redirected. Silently ignoring--offlinewhile going to the network would be a trap. Raw mode accepts them all since it resolves nothing. -
--temp-local-repositorycleanup is race-safe:deleteRecursivelyusesFiles.deleteIfExists(idempotent), and the shutdown hook + finally block can overlap harmlessly. The "delete first, deregister second" ordering is correct — the alternative window where a signal arrives after the hook is removed but before deletion runs would leak the directory. -
System.setProperty(MAVEN_LOGGER_DEFAULT_LOG_LEVEL, "error")inconfigureLoggingis a JVM-global side effect that leaks aftermvnval --format jsoninmvnsh. The next command'sconfigureLoggingoverwrites it, so it's cosmetic noise (an INFO log line fromMavenSimpleConfigurationnoting the override), not a correctness bug. -
Shell integration (
BuiltinShellCommandRegistryFactoryaddingmvnval) follows the same pattern asmvnencandmvnup. -
Reporterinterface dropped in favour ofstaticmethods onTextReporter/JsonReporterdelegated throughOutputFormatenum abstract method — simpler, no indirection for a two-element hierarchy. -
resolvePomsnormalises paths beforedistinct()— fixes"pom.xml" "./pom.xml"being treated as two files. TestshouldReadAPomNamedTwiceOncecovers it. -
Test coverage is thorough:
WiringTests.shouldRegisterTransportsexercises the realValidateInvoker(not the test seam) overfile://transport;EffectiveTestscovers inherited problems, parent resolution, refused options, aimed/temp repositories, and argument-order independence.
Solid follow-up. No issues found.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
Default is Effective runs the raw pass first.
The shared session I undid. It makes the verdict depend on argument order: derived sessions share Your javadoc sketch has |
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit 5b080ab..9c07cfd — clean fix, no issues
New commit assessment (9c07cfd): resolvePoms path deduplication fix.
Path::normalize only collapsed ./pom.xml vs pom.xml. The new sameFileSamePath uses toRealPath() which also resolves symlinks and case-insensitive filesystem equivalence (Windows/macOS: pom.xml vs POM.XML). Fallback to normalize() on IOException is correct — non-existent files reach unusable() downstream.
Test correctly handles platforms without symlink support (Windows without developer mode).
All previous findings remain addressed. No new issues.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
@gnodet, the CLI is ready for review. Here is the output from the unpacked distribution at I ran all nine fixture files in both modes, then checked batch output, JSON, invalid arguments, the Machine-specific paths are shown as
|
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit 9c07cfd..eaabc88 — clean improvement, one minor leak in the test
Previous findings status: All previously raised findings (rename buildRaw → validate, clearRequestScopedCache removal, session-per-POM revert, effective mode, lazy StringBuilder, path deduplication via toRealPath()) remain addressed. No regressions.
New commit assessment (eaabc887 — "Name a POM in the report the way the caller named it"):
-
TextReporter.display()relative-path logic is correct.realPath()canonicalizes bothcwdandpombeforestartsWith, so symlink-traversed working directories (macOS/var→/private/var) don't produce../../private/var/...paths. Fallback tonormalize()on IOException handles the non-existent path case. -
JSON keeps absolute paths — correct decision, well-documented in the
OutputFormat.JSONoverride comment. A machine-readable document consumed elsewhere must not depend on the producer's cwd. -
OutputFormat.report()signature change (addedPath cwd) is package-private, so no backward compatibility concern. -
TestUtils.renderusesPaths.get("/elsewhere")— ensures existingReporterTestassertions exercise the absolute-path branch (POM paths never start with/elsewhere). Clean. -
shouldPrintPathsRelativeToTheWorkingDirectorytest — exercises both branches correctly (relative for in-cwd, absolute for outside-cwd). One issue noted below.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit eaabc88..135daf4 — previous finding addressed, no new issues
Previous finding status:
- ✅
Files.createTempDirectory("mvnval-outside-")leak (gnodet-bot) — Addressed. The temp directory is now wrapped intry/finallywith leaf-firstdeleteIfExistscleanup: file →far/→ root. Ordering is correct,deleteIfExistsis safe if creation failed partway through, and the test still exercises the absolute-path branch (the temp dir is genuinely outside@TempDir).
Clean fix.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit 135daf4..8d8f8b8 — two bugs fixed, no new issues
Previous findings status: All previously raised findings remain addressed. No regressions.
New commit assessment (8d8f8b88 — "Honor mvnval property overrides and Ctrl+C"):
Two independent bugs fixed in one commit:
-
User properties not reaching the model builder —
validateAllbuiltModelBuilderRequestwithoutuserProperties, so-Dproperty=valuefrom the CLI was shadowed by POM<properties>. The fix passescontext.protoSession.getUserProperties()into the request builder. TheModelBuilderRequestis now built once per POM invalidateAlland threaded throughvalidateOne→ValidationMode.problemsFor, which also simplifiesValidationMode— therequest()factory and theSession/Pathparameters are gone, replaced by a singleModelBuilderRequest. InEFFECTIVEmode,ModelBuilderRequest.builder(request).requestType(BUILD_EFFECTIVE).build()correctly copiesuserPropertiesvia the copy constructor (line 202 ofModelBuilderRequest.java).shouldLetUserPropertiesOverridePomPropertiescovers both modes. -
Ctrl+C interrupted the wrong thread — the old
signal -> Thread.currentThread().interrupt()ran on the signal dispatch thread, not the validation thread. The fix capturesThread.currentThread()before the try block and the handler callsvalidationThread.interrupt(). AnAtomicBoolean cancellationRequestedsurvivesThread.interrupted()calls inside the model builder. Previous handler restored infinally; interrupt flag cleared on all cancellation paths (canceled()and the outerfinally).shouldCancelFromAnotherThreadAfterTheModelBuilderClearsTheInterruptfires INT fromCompletableFuture.runAsync, verifies the interrupt reached the right thread, confirms handler restoration, and checks that only one POM was attempted.
Static analysis: ast-grep flagged the two catch (Exception e) blocks — both are pre-existing, intentional, and documented (same pattern as mvnenc/mvnup).
Solid fixes with thorough test coverage.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
This comment has been minimized.
This comment has been minimized.
|
I pushed three improvements on top of this PR: 1. Suppress resolver noise in text mode
2. Extract line/column from
3. XML source context display (
Example output: |
@ikxeno you need to add the first line with a checked box |
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 8d8f8b8..3700924 — one real bug in the new session-mutation helpers
New commits assessed:
2c1a714bundle workspace reader for effective mode, honour -o61fa4bcIT for bundle workspace reader and --offlinebe15945quiet resolver noise, add line location and XML context display37009240fix color detection — use MessageUtils.isColorEnabled() directly
Previous findings status: All previously raised findings remain addressed.
New findings:
-
⚠️ withOffline/withWorkspaceReader— clone attempt silently falls back to in-place mutation — the Javadoc describes a clone mechanism that does not work.session.withLocalRepository(session.getLocalRepository())triggers theObjects.equals(basePath, localRepository.path())short-circuit inAbstractSession.withLocalRepository(), so it returnsthis— no clone.rsession.setOffline(true)andrsession.setWorkspaceReader(reader)then mutate the original session in-place. The code happens to work today because the original session is not reused aftervalidateAllmutates it, but the invariant stated in the Javadoc is false, and any future code that passes the same session to two independent callers will find the second caller has offline/workspace-reader state it did not set. See inline comments. -
ℹ️
TextReporter.contextLinesre-reads the file once per problem — low severity: POMs are small. See inline comment.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 8d8f8b8..3700924 — one real bug in the new session-mutation helpers
New commits assessed:
2c1a714bundle workspace reader for effective mode, honour -o61fa4bcIT for bundle workspace reader and --offlinebe15945quiet resolver noise, add line location and XML context display37009240fix color detection — useMessageUtils.isColorEnabled()directly
Previous findings status: All previously raised findings remain addressed.
New findings:
-
⚠️ withOffline/withWorkspaceReader— clone attempt silently falls back to in-place mutation — the Javadoc describes a clone mechanism that does not work.session.withLocalRepository(session.getLocalRepository())triggers theObjects.equals(basePath, localRepository.path())short-circuit inAbstractSession.withLocalRepository(), so it returnsthis— no clone.rsession.setOffline(true)andrsession.setWorkspaceReader(reader)then mutate the original session in-place. The code happens to work today because the original session is not reused aftervalidateAllmutates it, but the invariant stated in the Javadoc is false, and any future code that passes the same session to two independent callers will find the second caller has offline/workspace-reader state it did not set. See inline comments. -
ℹ️
TextReporter.contextLinesre-reads the file once per problem —Files.readAllLinesis called for every problem in a report, even when multiple problems share the same source file. Low severity for a CLI validation tool (POMs are small), but a singleMap<Path, List<String>>cache would eliminate the redundancy.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
The Please add one of the following lines (with the box checked
or
Once the description is updated, the check will re-run and clear automatically. |
gnodet
left a comment
There was a problem hiding this comment.
Re-review after commit e6239a3 — previous findings addressed, merge conflict resolved
Previous findings status:
-
✅
withOffline/withWorkspaceReader— clone attempt silently falls back to in-place mutation (gnodet-bot) — Addressed. The broken-clone pretense is gone. Both helpers now directly cast toDefaultRepositorySystemSessionand mutate in-place, with accurate Javadoc stating the safety contract (validateAllreassignssessionimmediately and does not retain the pre-mutation reference). Clean fix. -
ℹ️
TextReporter.contextLinesre-reads the file once per problem — low severity, not blocking. Can be addressed in a follow-up if desired.
Additional changes in this commit:
module-info.java—exports org.apache.maven.api.cli.mvnvaladded to themaven-api-climodule descriptor. Correct.- IT settings fix — test isolation improvement.
Merge conflict with master: Resolved. Both branches added module-info.java for maven-api-cli; the merge kept the exports org.apache.maven.api.cli.mvnval line from this branch.
Remaining blocker: The license-declaration CI check fails because the PR description does not contain a checked [x] license declaration. @ikxeno, please edit the PR description to add a checked checkbox — for example: - [x] I hereby grant Apache Software Foundation (ASF) a license to reproduce, modify, and distribute my contribution. The CI bot will auto-resolve the failure once the description is updated.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet
left a comment
There was a problem hiding this comment.
Re-review after commits 3700924..61ac635 — clone bug fixed, clean
Previous findings status:
-
✅
withOffline— clone never happens; Javadoc claimed false invariant (gnodet-bot) — Addressed ine6239a3. The brokenwithLocalRepository(same-repo)clone attempt is removed. The method now directly casts toDefaultRepositorySystemSessionand mutates in-place, with a comment that explicitly documents the safety assumption: "Safe only becausevalidateAllreassigns session immediately and does not retain the pre-mutation reference." The false Javadoc is gone. Honest and correct. -
✅
withWorkspaceReader— same broken-clone pattern (gnodet-bot) — Addressed ine6239a3. Same fix applied consistently. The misleading "it does not mutate the original session, which the tests may reuse across runs" Javadoc is removed entirely.
New changes assessment (e6239a3 — "fix withOffline/withWorkspaceReader clone, module-info export, IT settings"):
module-info.javaexport — addsapi/maven-api-climodule exports needed by the newmvnvalpackages. Correct; without this the module system would block cross-module access at runtime.- IT settings fix — adjusts the
BundleWorkspaceReaderIT to account for real settings-derived repository configuration. No new logic, test correction only.
All previous findings remain addressed. No new issues.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit e6239a3 — previous findings addressed, clean fix
Previous findings status:
-
✅
withOfflineclone never happens (gnodet-bot) — Addressed. Correctly drops the brokenwithLocalRepository(same-path)clone attempt and embraces honest in-place mutation with a clear safety comment. The session is fresh fromcreateSession()and local tovalidateAll()— no external reference can observe the mutation. -
✅
withWorkspaceReadersame broken-clone pattern (gnodet-bot) — Addressed. Same fix applied.setWorkspaceReader()now runs on the right resolver session.
New commit assessment (e6239a3):
ValidateInvoker.java— in-place mutation is correct and the inline safety comment explains the invariant clearly.module-info.java— conflict resolved cleanly;mvnvalexport is present and all 9 leaf packages are exported.MavenITmng8650MvnvalBundleWorkspaceReaderTest.java—newVerifier(testDir, null)correctly uses thePathoverload and skips the remote-settings fixture that is irrelevant formvnval(which derives its own repositories).
One minor nit on the Javadoc (inline).
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet
left a comment
There was a problem hiding this comment.
Re-review after commit e6239a3 / 61ac635 — previous findings addressed, no new issues
Previous findings status:
-
✅
withOffline— clone never happens; Javadoc claimed false invariant — Addressed ine6239a3. The brokenwithLocalRepository(same-repo)clone attempt is removed. The method now directly casts toDefaultRepositorySystemSessionand mutates in-place, with an accurate comment documenting the safety assumption. Correct fix. -
✅
withWorkspaceReader— same broken-clone pattern — Addressed ine6239a3. Same direct-cast-and-mutate approach, misleading Javadoc removed.
ℹ️ TextReporter.contextLines file re-read per problem — low severity, not blocking for a CLI tool operating on small POMs. Acceptable to defer.
CI: license-declaration now passes. All inline threads resolved. No remaining blockers.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 3700924..069f377 — previous findings addressed, one Javadoc nit self-corrected
Previous findings status:
- ✅
withOffline/withWorkspaceReader— clone attempt silently falls back to in-place mutation (gnodet-bot) — Addressed ine6239a32. The broken-clone pretense is gone. Both helpers now directly cast toDefaultRepositorySystemSessionand mutate in-place, with accurate inline comments stating the safety contract (validateAllcreates a fresh session viacreateSession()at line 204 and does not retain a reference after the call returns). Clean and honest.
New commit assessment (069f377d — "fix: update withOffline Javadoc to reflect in-place mutation"):
- The Javadoc at line 376 previously said "by cloning the underlying resolver session with offline set to true" — inconsistent with the inline comment introduced in
e6239a32(which correctly said "Mutate in-place").069f377dupdates the Javadoc to "by setting offline to true on the underlying resolver session." Accurate and consistent with the implementation.
All previous findings remain addressed. No new issues.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commit 61ac635..069f377 — previous finding addressed, no new issues
Previous finding status:
- ✅ Stale Javadoc in
withOffline(gnodet-bot) — Addressed. The phrase "by cloning the underlying resolver session with offline set to true" is replaced with "by setting offline to true on the underlying resolver session," which accurately reflects the in-place mutation semantics.
No new issues introduced. The single-line Javadoc correction is correct and complete.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
Hi, |
gnodet
left a comment
There was a problem hiding this comment.
Re-review after commit fd9b90e — test-only fixes, no new issues
Previous findings status: All previously raised findings remain addressed.
New commit assessment (fd9b90e — "Use native paths and raw mode in mvnval tests"):
-
ValidateInvokerTest—Path.of("near", "pom.xml")replaces the hardcoded"near/pom.xml"string. Correct Windows-portability fix: path separator must match the platform's separator in the assertion. -
MavenITgh10442MvnvalValidatePomTest— Adds--mode rawto the three existing ITs. The commit message explains why: the Verifier injects--install-settings, whichmvnvalin effective mode rejects (since effective mode derives its own repository configuration and does not allow external settings). Raw mode has no such restriction. Correct fix — the ITs were failing in effective mode for a legitimate reason, not a bug.
No production code changes. No regressions.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review after commits 3700924..fd9b90e — all previous findings addressed
New commits assessed:
e6239a3mvnval: fix withOffline/withWorkspaceReader clone, module-info export, IT settings61ac635Merge remote-tracking branch 'origin/master'069f377fix: update withOffline Javadoc to reflect in-place mutationfd9b90eUse native paths and raw mode in mvnval tests
Previous findings status:
-
✅
withOffline/withWorkspaceReader— clone never happens (HIGH) — Fixed ine6239a3. The brokensession.withLocalRepository(session.getLocalRepository())clone attempt is removed; both methods now mutate the underlyingDefaultRepositorySystemSessionin-place with a clear comment explaining the safety invariant ("Safe only because validateAll reassigns session immediately and does not retain the pre-mutation reference"). The stale Javadoc phrase "by cloning the underlying resolver session" is gone (069f377). Fix is correct:ApiRunner.createSession()does not freeze the session, and@BeforeEachcreates a fresh shared session per test, so there is no cross-test mutation hazard. -
ℹ️
TextReporter.contextLinesfile re-read (LOW) — Informational, no action expected. Still present, still low-severity for a CLI validation tool.
New commit assessment:
module-info.java—maven-api-clinow exportsorg.apache.maven.api.cli.mvnval. Required for module-system access toValidateOptionsand friends. Correct.Path.of("near", "pom.xml")instead of"near/pom.xml:"in the test — correct Windows cross-platform fix.- ITs switched to
--mode raw— Verifier injects--install-settingsby default, which effective mode rightly rejects; raw mode is the correct scope for these tests. newVerifier(testDir, null)instead ofnewVerifier(testDir.toString())— uses the overload that does not inject install settings.
No new issues found.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
|
Thanks for your work on this. I've pushed Could you please approve the CI run for the updated commit? |
|
The maven-site documentation is ready: apache/maven-site#1705 Adds:
|
Documentation added to apache/maven-site#1705
- Add ModelBuilderSession.validate() API method that collects all problems (errors and warnings) instead of throwing on the first error, enabling complete diagnostic reporting; declared default so existing implementations keep compiling unchanged - Add mvnval CLI tool reachable as `mvnval`, `mvn --val`, and from mvnsh; takes any number of POM files (defaults to ./pom.xml), writes text or JSON output, and returns structured exit codes: 0=clean, 1=errors, 2=bad usage, 3=cancelled, 4=warnings-only - Two validation modes: --mode raw (no repository access, works offline and on unpublished POMs) and --mode effective (default, resolves parents and BOMs, runs all checks including those needing inherited values) - Bundle workspace reader for effective mode: pre-scans all given POMs to build a GAV index so parent/BOM lookups among the bundle are answered from disk, making the verdict order-independent and avoiding redundant downloads - Honour -o/--offline in effective mode; refuse -s/-ps/-is (cannot redirect the settings ApiRunner reads at session-creation time) - Security hardening: no core extensions loaded, no container stood up, no maven.ext.class.path honoured; .mvn/jvm.config still reaches the launcher (documented in THREAT_MODEL.md) - --local-repository and --temp-local-repository options to aim or isolate the local repository; throwaway directory deleted on exit and on SIGTERM - Text output shows coloured severity labels and surrounding XML source context around each problem location; JSON output keeps absolute paths - Deduplicate POMs named multiple times (normalise to real path via toRealPath); print paths relative to working directory in text output - Add integration tests covering raw/effective validation, bundle workspace reader, offline mode, and mvnsh registration
fd9b90e to
327d5b7
Compare


Fixes #10442
This was gnodet's own request in MNG-8650, March 2025, and it moved to the 4.1.0
milestone rather than getting dropped:
My own reason sits downstream of that. I maintain Java packaging for ALT Linux,
where builds run offline and our Maven and Gradle plugins read the POMs we ship.
A POM that parses but isn't valid breaks them during a rebuild, nowhere near the
actual mistake.
Takes any number of POMs, defaults to
./pom.xml, writes text or--format json.Exit 0 when nothing was reported, 1 when anything was rejected, 2 on bad usage,
3 on Ctrl+C, 4 when only warnings were. Reachable as
mvnval, asmvn --val,and inside
mvnsh.Two modes, and one contains the other
--mode rawreads the file and raw models. It reaches no repository, so it worksoffline and on a POM whose parent is not published yet, which is the Central case:
a POM turning up there is on its own. What it cannot see is anything inheritance
introduces, such as a dependency whose version lives in the parent's
dependencyManagement.--mode effectiveis the default. It runs the raw pass and then builds theeffective model, so parents and imported boms are resolved and the checks needing
them run too. It keeps the raw pass because the effective build reports nothing
about the reactor around a POM: on its own it passes a project whose declared
subproject is not on disk, which
mvnrefuses to read.The default reaches the network and caches what it fetches, like any Maven
command.
--local-repositoryaims that somewhere else,--temp-local-repositoryat a directory made for the run and deleted when it ends, and
maven.repo.localworks as it does elsewhere.
-o,-s,-psand-isare refused outside rawmode rather than ignored: resolution runs on a session built from the default
settings files and cannot be redirected, and a gate that passed
-oand got anetwork call would be worse off than one told no.
Why not
mvn -f pom.xml validateBecause that needs a project you can build, and it stops at the first thing it
cannot resolve. This reads POMs and reports on all of them, one exit code for the
batch, and
--mode rawneeds no repository at all.Why a new API method
buildRawModel(request)already exists and is not enough: it returns theModeland drops the problem collector, so warnings never reach the caller.
build()keeps the problems but throws as soon as validation reports an error, so a POM
with one error and four warnings tells you about the error only.
Named
validaterather thanbuildRawso the name says what the caller gets andnot how far the pipeline runs.
default, not abstract, so anything implementingModelBuilderSessionkeeps compiling untouched. The interface promises only whatevery implementation must keep; how far this one runs is documented on the
override.
Decisions worth arguing about
A session per POM, not one for the run. I wrote the shared session first, as
asked. It makes the verdict depend on argument order: derived sessions share
mappedSources, so agroupId:artifactIdregistered while reading an earlier POManswers a later POM's parent lookup. Two files given one way came back clean and
the other way came back with an error about the wrong parent. Sharing bought no
reading either, since every pass walks the reactor from the root again.
The repositories come from the settings, derived here.
ApiRunner.createSessionasks its injector for an unqualified
Session, andInjectorImplregisters aqualified
@Providesunder the unqualified key as well, so a provider belonging toanother tool can answer and bring its own hardcoded repositories. Deriving the list
gives the same answer whichever session came back, and keeps the repositories an
operator declared. Worth an issue of its own; I did not want to fix the injector
from here.
The reactor is mapped before the POM is read. A 4.1.0 subproject may leave out
its parent version, and it is taken from the parent's file model. Without the walk
a perfectly valid subproject fails with
'parent.version' is missing.A reactor module that fails to load is logged, not reported.
loadFilePomreports that failure against the caller's result, so before this change
mvnval a/pom.xmlsaida/pom.xmlwas broken when the culprit wasb/pom.xml.The flag is scoped to
validate;build()is untouched and still fails on abroken module, because a build that silently skipped one would be worse.
Warnings exit 4. Codes 0 to 3 mean the same thing across the Maven 4 tools,
and 3 is already
CANCELEDinmvnencandmvnup. A gate has to tell "this POMhas warnings" from "mvnval broke" and from "somebody hit Ctrl+C", so warnings got
the next free code.
One problem reported twice is collapsed in the tool. The parent version check
sits in both
validateFileModelandvalidateRawModel, so the model builder handsthe same finding over twice. I collapsed it in
Reportrather than touching thevalidator, since changing that changes
mvn.JSON assembled by hand. No JSON library is on the CLI classpath and I would
rather not put one there for one output format. Non-ASCII is escaped as
\uXXXXbecause the writer's charset is the console's, which on Windows is routinely not
UTF-8, and a path can carry an unpaired surrogate that no charset encodes.
--format jsonalso quietens the log, since the document and the log sharestandard output and a CI runner in debug mode was enough to stop the output being
JSON.
No container is stood up.
LookupInvokeronly ever builds aProtoSessionand
ModelBuilderRequestneeds a fullSession, so the session is built increateSession, with the transports resolution needs, asmvnupdoes. Nothingbeside the POM can make this process load code:
.mvn/extensions.xml,maven.ext.class.pathand.mvn/settings.xmlnext to the file are not read..mvn/jvm.configstill reaches the launcher, as it does for every Maven tool.THREAT_MODEL.mdgets a row. It reads operator POMs and emits their contentinto a machine-readable document, and in the default mode it fetches from URLs the
POM itself chose. The row says that rather than claiming a containment that does
not hold.
Checked
mvn verifyonmaven-api-cli,maven-api-core,maven-implandmaven-cli.Checkstyle clean, javadoc clean under doclint. Distribution built and driven from
the unpacked archive.
Over the 40 POMs this repository builds from, both modes are clean. Over all 94
including test projects, six are flagged, and all six are fixtures that are broken
on purpose. Against five published POMs pulled from Central, both modes agree:
io.netty:netty-all:4.1.115.Finalhas ten duplicate dependency declarations, andguava, spring-core, commons-lang3 and jackson-databind are clean. Aimed at an
empty local repository the default mode fetched nine parent and bom POMs and
reached the same verdict, so resolution is exercised end to end.
Order independence is asserted in a test: two roots sharing
groupId:artifactId,validated in both orders, same problems.
--temp-local-repositoryis deleted onevery exit and on a signal, checked by killing the process at eight points through
a run.
--format jsonparses as one document, including underRUNNER_DEBUG=1.The shell command was driven through a pseudo terminal.
Two ITs fail on my machine for reasons this branch does not touch, and I have not
checked them against
master:MavenITmng4428FollowHttpRedirectTest.testitHttpsToHttps,which is HTTPS transport, and
MavenITmng7045DropUselessAndOutdatedCdiApiTest, whereGroovy 4.0.28 dies with "BUG! exception in phase 'semantic analysis'" on JDK 25 after
the model has already built.
License