[MNG-8340] Resolve parent according to the exact model location (#1857)

This commit is contained in:
Guillaume Nodet 2024-11-13 20:26:56 +01:00 committed by GitHub
parent 903cf59b0b
commit 46707e0f28
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 252 additions and 167 deletions

View File

@ -49,21 +49,26 @@ public interface ModelBuilderRequest {
*/ */
enum RequestType { enum RequestType {
/** /**
* The request is for building a model from a POM file in a project on the filesystem. * The request is for building an initial model from a POM file in a project on the filesystem.
*/ */
BUILD_POM, BUILD_PROJECT,
/** /**
* The request is for building the consumer POM. * The request is for rebuilding the effective POM in a project on the filesystem.
*/ */
CONSUMER_POM, BUILD_EFFECTIVE,
/**
* The request is used specifically to parse the POM used as a basis for creating the consumer POM.
* This POM will not ungergo any profile activation.
*/
BUILD_CONSUMER,
/** /**
* The request is for building a model from a parent POM file from a downloaded artifact. * The request is for building a model from a parent POM file from a downloaded artifact.
*/ */
PARENT_POM, CONSUMER_PARENT,
/** /**
* The request is for building a model from a dependency POM file from a downloaded artifact. * The request is for building a model from a dependency POM file from a downloaded artifact.
*/ */
DEPENDENCY CONSUMER_DEPENDENCY
} }
/** /**

View File

@ -21,14 +21,9 @@ package org.apache.maven.internal.transformation.impl;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.maven.api.SessionData; import org.apache.maven.api.SessionData;
@ -44,7 +39,6 @@ import org.apache.maven.api.services.ModelBuilderException;
import org.apache.maven.api.services.ModelBuilderRequest; import org.apache.maven.api.services.ModelBuilderRequest;
import org.apache.maven.api.services.ModelBuilderResult; import org.apache.maven.api.services.ModelBuilderResult;
import org.apache.maven.api.services.ModelSource; import org.apache.maven.api.services.ModelSource;
import org.apache.maven.api.services.Source;
import org.apache.maven.api.services.model.LifecycleBindingsInjector; import org.apache.maven.api.services.model.LifecycleBindingsInjector;
import org.apache.maven.internal.impl.InternalSession; import org.apache.maven.internal.impl.InternalSession;
import org.apache.maven.model.v4.MavenModelVersion; import org.apache.maven.model.v4.MavenModelVersion;
@ -95,10 +89,9 @@ class DefaultConsumerPomBuilder implements ConsumerPomBuilder {
throws ModelBuilderException { throws ModelBuilderException {
InternalSession iSession = InternalSession.from(session); InternalSession iSession = InternalSession.from(session);
ModelBuilderRequest.ModelBuilderRequestBuilder request = ModelBuilderRequest.builder(); ModelBuilderRequest.ModelBuilderRequestBuilder request = ModelBuilderRequest.builder();
request.requestType(ModelBuilderRequest.RequestType.CONSUMER_POM); request.requestType(ModelBuilderRequest.RequestType.BUILD_CONSUMER);
request.session(iSession); request.session(iSession);
// in order to resolve parents, we need to fake being at the correct location request.source(ModelSource.fromPath(src));
request.source(new PomConsumerModelSource(project.getModel().getPomPath(), src));
request.locationTracking(false); request.locationTracking(false);
request.systemProperties(session.getSystemProperties()); request.systemProperties(session.getSystemProperties());
request.userProperties(session.getUserProperties()); request.userProperties(session.getUserProperties());
@ -208,63 +201,4 @@ class DefaultConsumerPomBuilder implements ConsumerPomBuilder {
.filter(r -> !org.apache.maven.api.Repository.CENTRAL_ID.equals(r.getId())) .filter(r -> !org.apache.maven.api.Repository.CENTRAL_ID.equals(r.getId()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
static class PomConsumerModelSource implements ModelSource {
final Path path;
final Path src;
PomConsumerModelSource(Path path, Path src) {
this.path = path;
this.src = src;
}
@Override
public Path getPath() {
return path;
}
@Override
public InputStream openStream() throws IOException {
return Files.newInputStream(src);
}
@Override
public String getLocation() {
return src.toString();
}
@Override
public Source resolve(String relative) {
return ModelSource.fromPath(path.resolve(relative));
}
@Override
public ModelSource resolve(ModelLocator locator, String relative) {
String norm = relative.replace('\\', File.separatorChar).replace('/', File.separatorChar);
Path path = getPath().getParent().resolve(norm);
Path relatedPom = locator.locateExistingPom(path);
if (relatedPom != null) {
return ModelSource.fromPath(relatedPom);
}
return null;
}
@Override
public boolean equals(Object o) {
return this == o
|| o.getClass() == getClass()
&& Objects.equals(path, ((PomConsumerModelSource) o).path)
&& Objects.equals(src, ((PomConsumerModelSource) o).src);
}
@Override
public int hashCode() {
return Objects.hash(path, src);
}
@Override
public String toString() {
return "PomConsumerModelSource[" + "path=" + path + ']';
}
}
} }

View File

@ -351,8 +351,8 @@ public class DefaultProjectBuilder implements ProjectBuilder {
ModelBuilderRequest.RequestType type = pomFile != null ModelBuilderRequest.RequestType type = pomFile != null
&& this.request.isProcessPlugins() && this.request.isProcessPlugins()
&& this.request.getValidationLevel() == ModelBuildingRequest.VALIDATION_LEVEL_STRICT && this.request.getValidationLevel() == ModelBuildingRequest.VALIDATION_LEVEL_STRICT
? ModelBuilderRequest.RequestType.BUILD_POM ? ModelBuilderRequest.RequestType.BUILD_EFFECTIVE
: ModelBuilderRequest.RequestType.PARENT_POM; : ModelBuilderRequest.RequestType.CONSUMER_PARENT;
MavenProject theProject = project; MavenProject theProject = project;
ModelBuilderRequest request = builder.source(modelSource) ModelBuilderRequest request = builder.source(modelSource)
.requestType(type) .requestType(type)
@ -489,7 +489,7 @@ public class DefaultProjectBuilder implements ProjectBuilder {
}; };
ModelBuilderRequest modelBuildingRequest = getModelBuildingRequest() ModelBuilderRequest modelBuildingRequest = getModelBuildingRequest()
.source(ModelSource.fromPath(pomFile.toPath())) .source(ModelSource.fromPath(pomFile.toPath()))
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.locationTracking(true) .locationTracking(true)
.recursive(recursive) .recursive(recursive)
.lifecycleBindingsInjector(injector) .lifecycleBindingsInjector(injector)
@ -780,7 +780,7 @@ public class DefaultProjectBuilder implements ProjectBuilder {
InternalSession internalSession = InternalSession.from(session); InternalSession internalSession = InternalSession.from(session);
modelBuildingRequest.session(internalSession); modelBuildingRequest.session(internalSession);
modelBuildingRequest.requestType(ModelBuilderRequest.RequestType.BUILD_POM); modelBuildingRequest.requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT);
modelBuildingRequest.profiles( modelBuildingRequest.profiles(
request.getProfiles() != null request.getProfiles() != null
? request.getProfiles().stream() ? request.getProfiles().stream()
@ -913,7 +913,7 @@ public class DefaultProjectBuilder implements ProjectBuilder {
} }
project.setPluginArtifactRepositories(pluginRepositories); project.setPluginArtifactRepositories(pluginRepositories);
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM) { if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
try { try {
ProjectRealmCache.CacheRecord record = ProjectRealmCache.CacheRecord record =
projectBuildingHelper.createProjectRealm(project, model3, projectBuildingRequest); projectBuildingHelper.createProjectRealm(project, model3, projectBuildingRequest);

View File

@ -77,7 +77,7 @@ public class ConsumerPomBuilderTest extends AbstractRepositoryTestCase {
Model orgModel = mbs.build(ModelBuilderRequest.builder() Model orgModel = mbs.build(ModelBuilderRequest.builder()
.session(InternalSession.from(session)) .session(InternalSession.from(session))
.source(ModelSource.fromPath(file)) .source(ModelSource.fromPath(file))
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.build()) .build())
.getEffectiveModel(); .getEffectiveModel();
@ -103,7 +103,7 @@ public class ConsumerPomBuilderTest extends AbstractRepositoryTestCase {
Model orgModel = mbs.build(ModelBuilderRequest.builder() Model orgModel = mbs.build(ModelBuilderRequest.builder()
.session(InternalSession.from(session)) .session(InternalSession.from(session))
.source(ModelSource.fromPath(file)) .source(ModelSource.fromPath(file))
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.build()) .build())
.getEffectiveModel(); .getEffectiveModel();

View File

@ -200,40 +200,42 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
public ModelBuilderSession newSession() { public ModelBuilderSession newSession() {
return new ModelBuilderSession() { return new ModelBuilderSessionImpl();
DefaultModelBuilderSession mainSession;
/**
* Builds a model based on the provided ModelBuilderRequest.
*
* @param request The request containing the parameters for building the model.
* @return The result of the model building process.
* @throws ModelBuilderException If an error occurs during model building.
*/
@Override
public ModelBuilderResult build(ModelBuilderRequest request) throws ModelBuilderException {
// Create or derive a session based on the request
DefaultModelBuilderSession session;
if (mainSession == null) {
mainSession = new DefaultModelBuilderSession(request);
session = mainSession;
} else {
session = mainSession.derive(request, new DefaultModelBuilderResult());
}
// Build the request
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM) {
// build the build poms
session.buildBuildPom();
} else {
// simply build the effective model
session.buildEffectiveModel(new LinkedHashSet<>());
}
return session.result;
}
};
} }
protected class DefaultModelBuilderSession implements ModelProblemCollector { protected class ModelBuilderSessionImpl implements ModelBuilderSession {
ModelBuilderSessionState mainSession;
/**
* Builds a model based on the provided ModelBuilderRequest.
*
* @param request The request containing the parameters for building the model.
* @return The result of the model building process.
* @throws ModelBuilderException If an error occurs during model building.
*/
@Override
public ModelBuilderResult build(ModelBuilderRequest request) throws ModelBuilderException {
// Create or derive a session based on the request
ModelBuilderSessionState session;
if (mainSession == null) {
mainSession = new ModelBuilderSessionState(request);
session = mainSession;
} else {
session = mainSession.derive(request, new DefaultModelBuilderResult());
}
// Build the request
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
// build the build poms
session.buildBuildPom();
} else {
// simply build the effective model
session.buildEffectiveModel(new LinkedHashSet<>());
}
return session.result;
}
}
protected class ModelBuilderSessionState implements ModelProblemCollector {
private static final Pattern REGEX = Pattern.compile("\\$\\{([^}]+)}"); private static final Pattern REGEX = Pattern.compile("\\$\\{([^}]+)}");
final Session session; final Session session;
@ -251,7 +253,7 @@ public class DefaultModelBuilder implements ModelBuilder {
List<RemoteRepository> externalRepositories; List<RemoteRepository> externalRepositories;
List<RemoteRepository> repositories; List<RemoteRepository> repositories;
DefaultModelBuilderSession(ModelBuilderRequest request) { ModelBuilderSessionState(ModelBuilderRequest request) {
this( this(
request.getSession(), request.getSession(),
request, request,
@ -274,7 +276,7 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
@SuppressWarnings("checkstyle:ParameterNumber") @SuppressWarnings("checkstyle:ParameterNumber")
private DefaultModelBuilderSession( private ModelBuilderSessionState(
Session session, Session session,
ModelBuilderRequest request, ModelBuilderRequest request,
DefaultModelBuilderResult result, DefaultModelBuilderResult result,
@ -296,26 +298,26 @@ public class DefaultModelBuilder implements ModelBuilder {
this.result.setSource(this.request.getSource()); this.result.setSource(this.request.getSource());
} }
DefaultModelBuilderSession derive(ModelSource source) { ModelBuilderSessionState derive(ModelSource source) {
return derive(source, new DefaultModelBuilderResult(result)); return derive(source, new DefaultModelBuilderResult(result));
} }
DefaultModelBuilderSession derive(ModelSource source, DefaultModelBuilderResult result) { ModelBuilderSessionState derive(ModelSource source, DefaultModelBuilderResult result) {
return derive(ModelBuilderRequest.build(request, source), result); return derive(ModelBuilderRequest.build(request, source), result);
} }
/** /**
* Creates a new session, sharing cached datas and propagating errors. * Creates a new session, sharing cached datas and propagating errors.
*/ */
DefaultModelBuilderSession derive(ModelBuilderRequest request) { ModelBuilderSessionState derive(ModelBuilderRequest request) {
return derive(request, new DefaultModelBuilderResult(result)); return derive(request, new DefaultModelBuilderResult(result));
} }
DefaultModelBuilderSession derive(ModelBuilderRequest request, DefaultModelBuilderResult result) { ModelBuilderSessionState derive(ModelBuilderRequest request, DefaultModelBuilderResult result) {
if (session != request.getSession()) { if (session != request.getSession()) {
throw new IllegalArgumentException("Session mismatch"); throw new IllegalArgumentException("Session mismatch");
} }
return new DefaultModelBuilderSession( return new ModelBuilderSessionState(
session, session,
request, request,
result, result,
@ -669,7 +671,7 @@ public class DefaultModelBuilder implements ModelBuilder {
try (PhasingExecutor executor = createExecutor()) { try (PhasingExecutor executor = createExecutor()) {
for (DefaultModelBuilderResult r : allResults) { for (DefaultModelBuilderResult r : allResults) {
executor.execute(() -> { executor.execute(() -> {
DefaultModelBuilderSession mbs = derive(r.getSource(), r); ModelBuilderSessionState mbs = derive(r.getSource(), r);
try { try {
mbs.buildEffectiveModel(new LinkedHashSet<>()); mbs.buildEffectiveModel(new LinkedHashSet<>());
} catch (ModelBuilderException e) { } catch (ModelBuilderException e) {
@ -815,7 +817,7 @@ public class DefaultModelBuilder implements ModelBuilder {
resultModel = pluginManagementInjector.injectManagement(resultModel, request, this); resultModel = pluginManagementInjector.injectManagement(resultModel, request, this);
// lifecycle bindings injection // lifecycle bindings injection
if (request.getRequestType() != ModelBuilderRequest.RequestType.DEPENDENCY) { if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
org.apache.maven.api.services.ModelTransformer lifecycleBindingsInjector = org.apache.maven.api.services.ModelTransformer lifecycleBindingsInjector =
request.getLifecycleBindingsInjector(); request.getLifecycleBindingsInjector();
if (lifecycleBindingsInjector != null) { if (lifecycleBindingsInjector != null) {
@ -831,7 +833,7 @@ public class DefaultModelBuilder implements ModelBuilder {
resultModel = modelNormalizer.injectDefaultValues(resultModel, request, this); resultModel = modelNormalizer.injectDefaultValues(resultModel, request, this);
if (request.getRequestType() != ModelBuilderRequest.RequestType.DEPENDENCY) { if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
// plugins configuration // plugins configuration
resultModel = pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, this); resultModel = pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, this);
} }
@ -853,9 +855,7 @@ public class DefaultModelBuilder implements ModelBuilder {
// effective model validation // effective model validation
modelValidator.validateEffectiveModel( modelValidator.validateEffectiveModel(
resultModel, resultModel,
request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
? ModelValidator.VALIDATION_LEVEL_STRICT
: ModelValidator.VALIDATION_LEVEL_MINIMAL,
request, request,
this); this);
@ -896,8 +896,7 @@ public class DefaultModelBuilder implements ModelBuilder {
private Model resolveParent(Model childModel) { private Model resolveParent(Model childModel) {
Model parentModel = null; Model parentModel = null;
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM if (isBuildRequest()) {
|| request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_POM) {
parentModel = readParentLocally(childModel); parentModel = readParentLocally(childModel);
} }
if (parentModel == null) { if (parentModel == null) {
@ -911,18 +910,30 @@ public class DefaultModelBuilder implements ModelBuilder {
Parent parent = childModel.getParent(); Parent parent = childModel.getParent();
String parentPath = parent.getRelativePath(); String parentPath = parent.getRelativePath();
if (parentPath != null && !parentPath.isEmpty()) { if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath); if (parentPath != null && !parentPath.isEmpty()) {
if (candidateSource == null) { candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
wrongParentRelativePath(childModel); if (candidateSource == null) {
return null; wrongParentRelativePath(childModel);
return null;
}
} else {
candidateSource =
resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
if (candidateSource == null && parentPath == null) {
candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, "..");
}
} }
} } else {
if (candidateSource == null) {
candidateSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()); candidateSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
} if (candidateSource == null) {
if (candidateSource == null && parentPath == null) { if (parentPath == null) {
candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, ".."); parentPath = "..";
}
if (!parentPath.isEmpty()) {
candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
}
}
} }
if (candidateSource == null) { if (candidateSource == null) {
@ -1056,7 +1067,7 @@ public class DefaultModelBuilder implements ModelBuilder {
buffer.append(" for ").append(ModelProblemUtils.toId(childModel)); buffer.append(" for ").append(ModelProblemUtils.toId(childModel));
} }
buffer.append(": ").append(e.getMessage()); buffer.append(": ").append(e.getMessage());
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM) { if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
buffer.append(" and parent could not be found in reactor"); buffer.append(" and parent could not be found in reactor");
} }
@ -1065,7 +1076,7 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
ModelBuilderRequest lenientRequest = ModelBuilderRequest.builder(request) ModelBuilderRequest lenientRequest = ModelBuilderRequest.builder(request)
.requestType(ModelBuilderRequest.RequestType.PARENT_POM) .requestType(ModelBuilderRequest.RequestType.CONSUMER_PARENT)
.source(modelSource) .source(modelSource)
.build(); .build();
@ -1163,13 +1174,13 @@ public class DefaultModelBuilder implements ModelBuilder {
// path correctly if it was not set in the input model // path correctly if it was not set in the input model
if (inputModel.getParent() != null && inputModel.getParent().getRelativePath() == null) { if (inputModel.getParent() != null && inputModel.getParent().getRelativePath() == null) {
String relPath; String relPath;
if (parentModel.getPomFile() != null if (parentModel.getPomFile() != null && isBuildRequest()) {
&& (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM
|| request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_POM)) {
relPath = inputModel relPath = inputModel
.getPomFile() .getPomFile()
.getParent() .getParent()
.relativize(parentModel.getPomFile().getParent()) .toAbsolutePath()
.relativize(
parentModel.getPomFile().toAbsolutePath().getParent())
.toString(); .toString();
} else { } else {
relPath = ".."; relPath = "..";
@ -1232,7 +1243,7 @@ public class DefaultModelBuilder implements ModelBuilder {
private List<Profile> getActiveProfiles( private List<Profile> getActiveProfiles(
Collection<Profile> interpolatedProfiles, DefaultProfileActivationContext profileActivationContext) { Collection<Profile> interpolatedProfiles, DefaultProfileActivationContext profileActivationContext) {
if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_POM) { if (isBuildRequestWithActivation()) {
return profileSelector.getActiveProfiles(interpolatedProfiles, profileActivationContext, this); return profileSelector.getActiveProfiles(interpolatedProfiles, profileActivationContext, this);
} else { } else {
return List.of(); return List.of();
@ -1254,7 +1265,7 @@ public class DefaultModelBuilder implements ModelBuilder {
setSource(modelSource.getLocation()); setSource(modelSource.getLocation());
logger.debug("Reading file model from " + modelSource.getLocation()); logger.debug("Reading file model from " + modelSource.getLocation());
try { try {
boolean strict = request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM; boolean strict = isBuildRequest();
try { try {
rootDirectory = request.getSession().getRootDirectory(); rootDirectory = request.getSession().getRootDirectory();
} catch (IllegalStateException ignore) { } catch (IllegalStateException ignore) {
@ -1335,8 +1346,7 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
} }
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM if (isBuildRequest()) {
|| request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_POM) {
model = model.withPomFile(modelSource.getPath()); model = model.withPomFile(modelSource.getPath());
Parent parent = model.getParent(); Parent parent = model.getParent();
@ -1437,9 +1447,7 @@ public class DefaultModelBuilder implements ModelBuilder {
setSource(model); setSource(model);
modelValidator.validateFileModel( modelValidator.validateFileModel(
model, model,
request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
? ModelValidator.VALIDATION_LEVEL_STRICT
: ModelValidator.VALIDATION_LEVEL_MINIMAL,
request, request,
this); this);
if (hasFatalErrors()) { if (hasFatalErrors()) {
@ -1459,12 +1467,9 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
private Model doReadRawModel() throws ModelBuilderException { private Model doReadRawModel() throws ModelBuilderException {
ModelBuilderRequest request = this.request;
Model rawModel = readFileModel(); Model rawModel = readFileModel();
if (!MODEL_VERSION_4_0_0.equals(rawModel.getModelVersion()) if (!MODEL_VERSION_4_0_0.equals(rawModel.getModelVersion()) && isBuildRequest()) {
&& (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM
|| request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_POM)) {
rawModel = transformFileToRaw(rawModel); rawModel = transformFileToRaw(rawModel);
} }
@ -1474,9 +1479,7 @@ public class DefaultModelBuilder implements ModelBuilder {
modelValidator.validateRawModel( modelValidator.validateRawModel(
rawModel, rawModel,
request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
? ModelValidator.VALIDATION_LEVEL_STRICT
: ModelValidator.VALIDATION_LEVEL_MINIMAL,
request, request,
this); this);
@ -1679,7 +1682,7 @@ public class DefaultModelBuilder implements ModelBuilder {
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
rootDirectory = null; rootDirectory = null;
} }
if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM && rootDirectory != null) { if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT && rootDirectory != null) {
Path sourcePath = importSource.getPath(); Path sourcePath = importSource.getPath();
if (sourcePath != null && sourcePath.startsWith(rootDirectory)) { if (sourcePath != null && sourcePath.startsWith(rootDirectory)) {
add( add(
@ -1694,13 +1697,13 @@ public class DefaultModelBuilder implements ModelBuilder {
try { try {
ModelBuilderRequest importRequest = ModelBuilderRequest.builder() ModelBuilderRequest importRequest = ModelBuilderRequest.builder()
.session(request.getSession()) .session(request.getSession())
.requestType(ModelBuilderRequest.RequestType.DEPENDENCY) .requestType(ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY)
.systemProperties(request.getSystemProperties()) .systemProperties(request.getSystemProperties())
.userProperties(request.getUserProperties()) .userProperties(request.getUserProperties())
.source(importSource) .source(importSource)
.repositories(repositories) .repositories(repositories)
.build(); .build();
DefaultModelBuilderSession modelBuilderSession = derive(importRequest); ModelBuilderSessionState modelBuilderSession = derive(importRequest);
// build the effective model // build the effective model
modelBuilderSession.buildEffectiveModel(importIds); modelBuilderSession.buildEffectiveModel(importIds);
importResult = modelBuilderSession.result; importResult = modelBuilderSession.result;
@ -1738,6 +1741,16 @@ public class DefaultModelBuilder implements ModelBuilder {
return cache.computeIfAbsent(source, tag, supplier); return cache.computeIfAbsent(source, tag, supplier);
} }
boolean isBuildRequest() {
return request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT
|| request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_EFFECTIVE
|| request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER;
}
boolean isBuildRequestWithActivation() {
return request.getRequestType() != ModelBuilderRequest.RequestType.BUILD_CONSUMER;
}
private List<Profile> interpolateActivations( private List<Profile> interpolateActivations(
List<Profile> profiles, DefaultProfileActivationContext context, ModelProblemCollector problems) { List<Profile> profiles, DefaultProfileActivationContext context, ModelProblemCollector problems) {
if (profiles.stream() if (profiles.stream()
@ -1816,7 +1829,7 @@ public class DefaultModelBuilder implements ModelBuilder {
} }
public Model buildRawModel(ModelBuilderRequest request) throws ModelBuilderException { public Model buildRawModel(ModelBuilderRequest request) throws ModelBuilderException {
DefaultModelBuilderSession build = new DefaultModelBuilderSession(request); ModelBuilderSessionState build = new ModelBuilderSessionState(request);
Model model = build.readRawModel(); Model model = build.readRawModel();
if (((ModelProblemCollector) build).hasErrors()) { if (((ModelProblemCollector) build).hasErrors()) {
throw build.newModelBuilderException(); throw build.newModelBuilderException();

View File

@ -123,7 +123,7 @@ public class DefaultModelInterpolator implements ModelInterpolator {
} }
protected List<String> getProjectPrefixes(ModelBuilderRequest request) { protected List<String> getProjectPrefixes(ModelBuilderRequest request) {
return request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_POM return request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT
? PROJECT_PREFIXES_4_0 ? PROJECT_PREFIXES_4_0
: PROJECT_PREFIXES_3_1; : PROJECT_PREFIXES_3_1;
} }

View File

@ -194,7 +194,7 @@ public class DefaultArtifactDescriptorReader implements ArtifactDescriptorReader
pomArtifact.getGroupId() + ":" + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion(); pomArtifact.getGroupId() + ":" + pomArtifact.getArtifactId() + ":" + pomArtifact.getVersion();
ModelBuilderRequest modelRequest = ModelBuilderRequest.builder() ModelBuilderRequest modelRequest = ModelBuilderRequest.builder()
.session(iSession) .session(iSession)
.requestType(ModelBuilderRequest.RequestType.DEPENDENCY) .requestType(ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY)
.source(ModelSource.fromPath(pomArtifact.getPath(), gav)) .source(ModelSource.fromPath(pomArtifact.getPath(), gav))
// This merge is on purpose because otherwise user properties would override model // This merge is on purpose because otherwise user properties would override model
// properties in dependencies the user does not know. See MNG-7563 for details. // properties in dependencies the user does not know. See MNG-7563 for details.

View File

@ -56,7 +56,7 @@ class ComplexActivationTest {
void testAndConditionInActivation() throws Exception { void testAndConditionInActivation() throws Exception {
ModelBuilderRequest request = ModelBuilderRequest.builder() ModelBuilderRequest request = ModelBuilderRequest.builder()
.session(session) .session(session)
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.source(ModelSource.fromPath(getPom("complex"))) .source(ModelSource.fromPath(getPom("complex")))
.systemProperties(Map.of("myproperty", "test")) .systemProperties(Map.of("myproperty", "test"))
.build(); .build();
@ -71,7 +71,7 @@ class ComplexActivationTest {
public void testConditionExistingAndMissingInActivation() throws Exception { public void testConditionExistingAndMissingInActivation() throws Exception {
ModelBuilderRequest request = ModelBuilderRequest.builder() ModelBuilderRequest request = ModelBuilderRequest.builder()
.session(session) .session(session)
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.source(ModelSource.fromPath(getPom("complexExistsAndMissing"))) .source(ModelSource.fromPath(getPom("complexExistsAndMissing")))
.build(); .build();
ModelBuilderResult result = builder.newSession().build(request); ModelBuilderResult result = builder.newSession().build(request);

View File

@ -47,7 +47,7 @@ class TestApiStandalone {
.build(ModelBuilderRequest.builder() .build(ModelBuilderRequest.builder()
.session(session) .session(session)
.source(ModelSource.fromPath(Paths.get("pom.xml").toAbsolutePath())) .source(ModelSource.fromPath(Paths.get("pom.xml").toAbsolutePath()))
.requestType(ModelBuilderRequest.RequestType.BUILD_POM) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
.recursive(true) .recursive(true)
.build()); .build());
assertNotNull(result.getEffectiveModel()); assertNotNull(result.getEffectiveModel());

View File

@ -0,0 +1,54 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.maven.it;
import java.io.File;
import java.util.List;
import org.apache.maven.shared.verifier.Verifier;
import org.apache.maven.shared.verifier.util.ResourceExtractor;
import org.junit.jupiter.api.Test;
/**
* This is a test set for <a href="https://issues.apache.org/jira/browse/MNG-8340">MNG-8340</a>.
*/
class MavenITmng8340GeneratedPomInTargetTest extends AbstractMavenIntegrationTestCase {
MavenITmng8340GeneratedPomInTargetTest() {
super("[3.8.6,4.0.0-beta-5),[4.0.0-beta-6,)");
}
/**
* Verify that the build succeeds.
*/
@Test
void testProjectWithShadePluginAndGeneratedPomUnderTarget() throws Exception {
File testDir = ResourceExtractor.simpleExtractResources(getClass(), "/mng-8340");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> l = verifier.loadLines(verifier.getLogFileName(), "UTF-8");
assertFalse(l.stream()
.anyMatch(i -> i.contains(
"[FATAL] 'parent.relativePath' points at '../../pom.xml' but no POM could be found")));
}
}

View File

@ -120,6 +120,7 @@ public class TestSuiteOrdering implements ClassOrderer {
* the tests are to finishing. Newer tests are also more likely to fail, so this is * the tests are to finishing. Newer tests are also more likely to fail, so this is
* a fail fast technique as well. * a fail fast technique as well.
*/ */
suite.addTestSuite(MavenITmng8340GeneratedPomInTargetTest.class);
suite.addTestSuite(MavenITmng8360SubprojectProfileActivationTest.class); suite.addTestSuite(MavenITmng8360SubprojectProfileActivationTest.class);
suite.addTestSuite(MavenITmng8347TransitiveDependencyManagerTest.class); suite.addTestSuite(MavenITmng8347TransitiveDependencyManagerTest.class);
suite.addTestSuite(MavenITmng8341DeadlockTest.class); suite.addTestSuite(MavenITmng8341DeadlockTest.class);

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven.it.mng8340</groupId>
<artifactId>root</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>child1</artifactId>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<id>shade</id>
<goals>
<goal>shade</goal>
</goals>
<phase>package</phase>
<configuration>
<dependencyReducedPomLocation>${basedir}/target/dr-pom.xml</dependencyReducedPomLocation>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven.it.mng8340</groupId>
<artifactId>root</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>child2</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.it.mng8340</groupId>
<artifactId>child1</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.maven.it.mng8340</groupId>
<artifactId>root</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>child1</module>
<module>child2</module>
</modules>
</project>