Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public interface ModelBuilder extends Service {

String MODEL_VERSION_4_1_0 = "4.1.0";

List<String> ALL_KNOWN_MODEL_VERSIONS = List.of(MODEL_VERSION_4_0_0, MODEL_VERSION_4_1_0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, all is kind of implied.

List<String> KNOWN_MODEL_VERSIONS = List.of(MODEL_VERSION_4_0_0, MODEL_VERSION_4_1_0);

ModelBuilderSession newSession();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import javax.xml.stream.XMLStreamException;

import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand All @@ -37,8 +36,6 @@
import org.apache.maven.api.feature.Features;
import org.apache.maven.api.model.Model;
import org.apache.maven.api.services.ModelBuilderException;
import org.apache.maven.internal.transformation.PomArtifactTransformer;
import org.apache.maven.model.v4.MavenStaxWriter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.artifact.ProjectArtifact;
import org.eclipse.aether.RepositorySystemSession;
Expand All @@ -55,15 +52,11 @@
*/
@Singleton
@Named
class ConsumerPomArtifactTransformer implements PomArtifactTransformer {
class ConsumerPomArtifactTransformer extends TransformerSupport {
private static final String CONSUMER_POM_CLASSIFIER = "consumer";

private static final String BUILD_POM_CLASSIFIER = "build";

private static final String NAMESPACE_FORMAT = "http://maven.apache.org/POM/%s";

private static final String SCHEMA_LOCATION_FORMAT = "https://maven.apache.org/xsd/maven-%s.xsd";

private final Set<Path> toDelete = new CopyOnWriteArraySet<>();

private final PomBuilder builder;
Expand Down Expand Up @@ -194,16 +187,4 @@ private Collection<Artifact> replacePom(Collection<Artifact> artifacts) {
}
return artifacts;
}

void write(Model model, Path dest) throws IOException, XMLStreamException {
String version = model.getModelVersion();
Files.createDirectories(dest.getParent());
try (Writer w = Files.newBufferedWriter(dest)) {
MavenStaxWriter writer = new MavenStaxWriter();
writer.setNamespace(String.format(NAMESPACE_FORMAT, version));
writer.setSchemaLocation(String.format(SCHEMA_LOCATION_FORMAT, version));
writer.setAddLocationInformation(false);
writer.write(w, model);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,16 @@
import javax.xml.stream.XMLStreamException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.maven.api.feature.Features;
import org.apache.maven.api.services.ModelBuilderException;
import org.apache.maven.internal.transformation.PomArtifactTransformer;
import org.apache.maven.api.model.Model;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.deployment.DeployRequest;
import org.eclipse.aether.installation.InstallRequest;

/**
* Inliner POM transformer.
Expand All @@ -40,28 +41,45 @@
*/
@Singleton
@Named
class PomInlinerTransformer implements PomArtifactTransformer {
@Override
public InstallRequest remapInstallArtifacts(RepositorySystemSession session, InstallRequest request) {
return request;
}

@Override
public DeployRequest remapDeployArtifacts(RepositorySystemSession session, DeployRequest request) {
return request;
}
class PomInlinerTransformer extends TransformerSupport {
protected static final Pattern PLACEHOLDER_EXPRESSION = Pattern.compile("\\$\\{(.+?)}");

@Override
public void injectTransformedArtifacts(RepositorySystemSession session, MavenProject currentProject)
throws IOException {
public void injectTransformedArtifacts(RepositorySystemSession session, MavenProject project) throws IOException {
if (!Features.consumerPom(session.getConfigProperties())) {
// TODO
try {
Model model = read(project.getFile().toPath());
String version = model.getVersion();
String newVersion = version;
int lastEnd = -1;
if (version != null) {
Matcher m = PLACEHOLDER_EXPRESSION.matcher(version.trim());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the Interpolator would be easier and safer here.

while (m.find()) {
String property = m.group(1);
if (!session.getConfigProperties().containsKey(property)) {
throw new IllegalArgumentException("Cannot inline property " + property);
}
String propertyValue =
(String) session.getConfigProperties().get(property);
if (lastEnd < 0) {
newVersion = version.substring(0, m.start());
} else {
newVersion += version.substring(lastEnd, m.start());
}
lastEnd = m.end();
newVersion += propertyValue;
}
if (!Objects.equals(version, newVersion)) {
model = model.withVersion(newVersion);
Path tmpPom = Files.createTempFile(
project.getArtifactId() + "-" + project.getVersion() + "-", ".xml");
write(model, tmpPom);
project.setFile(tmpPom.toFile());
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Matcher m = PLACEHOLDER_EXPRESSION.matcher(version.trim());
while (m.find()) {
String property = m.group(1);
if (!session.getConfigProperties().containsKey(property)) {
throw new IllegalArgumentException("Cannot inline property " + property);
}
String propertyValue =
(String) session.getConfigProperties().get(property);
if (lastEnd < 0) {
newVersion = version.substring(0, m.start());
} else {
newVersion += version.substring(lastEnd, m.start());
}
lastEnd = m.end();
newVersion += propertyValue;
}
if (!Objects.equals(version, newVersion)) {
model = model.withVersion(newVersion);
Path tmpPom = Files.createTempFile(
project.getArtifactId() + "-" + project.getVersion() + "-", ".xml");
write(model, tmpPom);
project.setFile(tmpPom.toFile());
}
}
handleVersion(session, project, version, -1, version, model);

could give dedicated attention to this concern. Operating on all the fields is kind of smell also.

    private static void handleVersion(RepositorySystemSession session, MavenProject project, String version, int lastEnd, String newVersion, Model model) throws IOException {
        Matcher m = PLACEHOLDER_EXPRESSION.matcher(version.trim());
        while (m.find()) {
            String property = m.group(1);
            if (!session.getConfigProperties().containsKey(property)) {
                throw new IllegalArgumentException("Cannot inline property " + property);
            }
            String propertyValue =
                    (String) session.getConfigProperties().get(property);
            if (lastEnd < 0) {
                newVersion = version.substring(0, m.start());
            } else {
                newVersion += version.substring(lastEnd, m.start());
            }
            lastEnd = m.end();
            newVersion += propertyValue;
        }
        if (!Objects.equals(version, newVersion)) {
            model = model.withVersion(newVersion);
            Path tmpPom = Files.createTempFile(
                    project.getArtifactId() + "-" + project.getVersion() + "-", ".xml");
            write(model, tmpPom);
            project.setFile(tmpPom.toFile());
        }
    }

} catch (XMLStreamException e) {
throw new IOException("Problem during inlining POM", e);
}
}
}

@Override
public void transform(MavenProject project, RepositorySystemSession session, Path src, Path tgt)
throws ModelBuilderException, XMLStreamException, IOException {
// TODO
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
Expand All @@ -37,6 +35,8 @@
import org.apache.maven.internal.transformation.TransformationFailedException;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.internal.impl.checksum.Sha1ChecksumAlgorithmFactory;
import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmHelper;

/**
* Transformed artifact is derived with some transformation from source artifact.
Expand Down Expand Up @@ -98,12 +98,12 @@ public synchronized File getFile() {
return null;
}
return target.toFile();
} catch (IOException | NoSuchAlgorithmException | XMLStreamException | ModelBuilderException e) {
} catch (IOException | XMLStreamException | ModelBuilderException e) {
throw new TransformationFailedException(e);
}
}

private String mayUpdate() throws IOException, NoSuchAlgorithmException, XMLStreamException, ModelBuilderException {
private String mayUpdate() throws IOException, XMLStreamException, ModelBuilderException {
String result;
Path src = sourcePathProvider.get();
if (src == null) {
Expand All @@ -113,7 +113,8 @@ private String mayUpdate() throws IOException, NoSuchAlgorithmException, XMLStre
Files.deleteIfExists(target);
result = "";
} else {
String current = sha1(src);
String current = ChecksumAlgorithmHelper.calculate(src, List.of(new Sha1ChecksumAlgorithmFactory()))
.get(Sha1ChecksumAlgorithmFactory.NAME);
String existing = sourceState.get();
if (!Files.exists(target) || !Objects.equals(current, existing)) {
pomArtifactTransformer.transform(project, session, src, target);
Expand All @@ -124,20 +125,4 @@ private String mayUpdate() throws IOException, NoSuchAlgorithmException, XMLStre
sourceState.set(result);
return result;
}

static String sha1(Path path) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
try (InputStream fis = Files.newInputStream(path)) {
byte[] buffer = new byte[SHA1_BUFFER_SIZE];
int read;
while ((read = fis.read(buffer)) != -1) {
md.update(buffer, 0, read);
}
}
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* 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.internal.transformation.impl;

import javax.xml.stream.XMLStreamException;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.maven.api.model.Model;
import org.apache.maven.api.services.ModelBuilderException;
import org.apache.maven.internal.transformation.PomArtifactTransformer;
import org.apache.maven.model.v4.MavenStaxReader;
import org.apache.maven.model.v4.MavenStaxWriter;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.deployment.DeployRequest;
import org.eclipse.aether.installation.InstallRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Support class.
*/
abstract class TransformerSupport implements PomArtifactTransformer {
protected final Logger logger = LoggerFactory.getLogger(getClass());

@Override
public InstallRequest remapInstallArtifacts(RepositorySystemSession session, InstallRequest request) {
return request;
}

@Override
public DeployRequest remapDeployArtifacts(RepositorySystemSession session, DeployRequest request) {
return request;
}

@Override
public void injectTransformedArtifacts(RepositorySystemSession session, MavenProject project) throws IOException {}

@Override
public void transform(MavenProject project, RepositorySystemSession session, Path src, Path tgt)
throws ModelBuilderException, XMLStreamException, IOException {
throw new IllegalStateException("This transformer does not use this call.");
}

protected static final String NAMESPACE_FORMAT = "http://maven.apache.org/POM/%s";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider grouping all fields like we would do for constructors: https://checkstyle.sourceforge.io/checks/coding/constructorsdeclarationgrouping.html


protected static final String SCHEMA_LOCATION_FORMAT = "https://maven.apache.org/xsd/maven-%s.xsd";

protected Model read(Path src) throws IOException, XMLStreamException {
MavenStaxReader reader = new MavenStaxReader();
try (InputStream is = Files.newInputStream(src)) {
return reader.read(is, false, null);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
MavenStaxReader reader = new MavenStaxReader();
try (InputStream is = Files.newInputStream(src)) {
return reader.read(is, false, null);
}
try (InputStream is = Files.newInputStream(src)) {
return new MavenStaxReader().read(is, false, null);
}

could inline.

}

protected void write(Model model, Path dest) throws IOException, XMLStreamException {
String version = model.getModelVersion();
Files.createDirectories(dest.getParent());
try (Writer w = Files.newBufferedWriter(dest)) {
MavenStaxWriter writer = new MavenStaxWriter();
writer.setNamespace(String.format(NAMESPACE_FORMAT, version));
writer.setSchemaLocation(String.format(SCHEMA_LOCATION_FORMAT, version));
writer.setAddLocationInformation(false);
writer.write(w, model);
}
}
Comment on lines +77 to +86
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
String version = model.getModelVersion();
Files.createDirectories(dest.getParent());
try (Writer w = Files.newBufferedWriter(dest)) {
MavenStaxWriter writer = new MavenStaxWriter();
writer.setNamespace(String.format(NAMESPACE_FORMAT, version));
writer.setSchemaLocation(String.format(SCHEMA_LOCATION_FORMAT, version));
writer.setAddLocationInformation(false);
writer.write(w, model);
}
}
Files.createDirectories(dest.getParent());
try (Writer w = Files.newBufferedWriter(dest)) {
write(model.getModelVersion(), w, new MavenStaxWriter())
}
}

could delegate as well.

}
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,7 @@ Model readParent(Model childModel, DefaultProfileActivationContext profileActiva
result.setParentModel(parentModel);
} else {
String superModelVersion = childModel.getModelVersion();
if (superModelVersion == null || !ALL_KNOWN_MODEL_VERSIONS.contains(superModelVersion)) {
if (superModelVersion == null || !KNOWN_MODEL_VERSIONS.contains(superModelVersion)) {
// Maven 3.x is always using 4.0.0 version to load the supermodel, so
// do the same when loading a dependency. The model validator will also
// check that field later.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ public void validateFileModel(Session s, Model m, int validationLevel, ModelProb
|| parent.getArtifactId() != null
&& !parent.getArtifactId().isEmpty())
&& validationLevel >= ModelValidator.VALIDATION_LEVEL_MAVEN_4_0
&& ModelBuilder.ALL_KNOWN_MODEL_VERSIONS.contains(m.getModelVersion())
&& ModelBuilder.KNOWN_MODEL_VERSIONS.contains(m.getModelVersion())
&& !Objects.equals(m.getModelVersion(), ModelBuilder.MODEL_VERSION_4_0_0)) {
addViolation(
problems,
Expand Down Expand Up @@ -374,7 +374,7 @@ public void validateFileModel(Session s, Model m, int validationLevel, ModelProb
} else if (validationLevel >= ModelValidator.VALIDATION_LEVEL_MAVEN_2_0) {
validateStringNotEmpty("modelVersion", problems, Severity.ERROR, Version.V20, m.getModelVersion(), m);

validateModelVersion(problems, m.getModelVersion(), m, ModelBuilder.ALL_KNOWN_MODEL_VERSIONS);
validateModelVersion(problems, m.getModelVersion(), m, ModelBuilder.KNOWN_MODEL_VERSIONS);

Set<String> modules = new HashSet<>();
for (int i = 0, n = m.getModules().size(); i < n; i++) {
Expand Down