diff --git a/pom.xml b/pom.xml index f7597d25c7c..24ef3d90fac 100644 --- a/pom.xml +++ b/pom.xml @@ -29,6 +29,7 @@ UTF-8 7.5.0 + 3.9.8 org.rascalmpl.shell.RascalShell 2 11 @@ -317,9 +318,10 @@ org/rascalmpl/uri/resolvers.config io/usethesource/vallang/type/types.config + META-INF/sisu/javax.inject.Named - - + + false @@ -514,5 +516,30 @@ icu4j 74.2 + + org.apache.maven + maven-embedder + ${maven-version} + + + org.apache.maven.plugins + maven-dependency-plugin + 3.7.1 + + + org.slf4j + slf4j-nop + 1.7.36 + + + org.apache.maven + maven-compat + ${maven-version} + + + org.apache.maven + maven-core + ${maven-version} + diff --git a/src/org/rascalmpl/library/util/Maven.java b/src/org/rascalmpl/library/util/Maven.java new file mode 100644 index 00000000000..59b678a3d5e --- /dev/null +++ b/src/org/rascalmpl/library/util/Maven.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2024, Rodin Aarssen, Swat.engineering + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.rascalmpl.library.util; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.cli.CliRequest; +import org.apache.maven.cli.MavenCli; +import org.codehaus.plexus.classworlds.ClassWorld; +import org.rascalmpl.uri.URIResolverRegistry; +import org.rascalmpl.uri.URIUtil; + +import io.usethesource.vallang.ISourceLocation; + +public class Maven { + /** + * Calls maven with the provided arguments. The working directory will be set to `manifestRoot`, + * which should contain a `pom.xml` file. If `outputFile` refers to an existing file, its contents + * will the read and returned after Maven concludes. + * + * Maven's output is fully suppressed. However, it is often possible to redirect (parts of) the output + * to a file. For instance, the output of `mvn dependency:build-classpath` can be redicted to a file + * by providing an additional argument `-Dmdep.outputFile=/path/to/file`. + */ + public static List runCommand(List args, ISourceLocation manifestRoot, Path outputFile) { + try { + ISourceLocation pomxml = URIUtil.getChildLocation(manifestRoot, "pom.xml"); + pomxml = URIResolverRegistry.getInstance().logicalToPhysical(pomxml); + manifestRoot = URIResolverRegistry.getInstance().logicalToPhysical(manifestRoot); + + if (!"file".equals(manifestRoot.getScheme())) { + throw new IllegalArgumentException("`manifestRoot` could not be resolved"); + } + + if (!URIResolverRegistry.getInstance().exists(pomxml)) { + throw new IllegalArgumentException("`manifestRoot` does not contain pom.xml"); + } + + var maven = new MavenCli(); + maven.doMain(buildRequest(args.toArray(String[]::new), manifestRoot)); + + if (outputFile != null && Files.exists(outputFile)) { + return Files.readAllLines(outputFile); + } + } catch (IOException | ReflectiveOperationException e) { + // Fall through to return the empty list + } + + return Collections.emptyList(); + } + + /** + * Calls maven with the provided arguments. The working directory will be set to `manifestRoot`, + * which should contain a `pom.xml` file. Maven's output is fully suppressed. + */ + public static void runCommand(List args, ISourceLocation manifestRoot) { + runCommand(args, manifestRoot, null); + } + + private static void setField(CliRequest req, String fieldName, Object value) throws ReflectiveOperationException { + var field = CliRequest.class.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(req, value); + } + + private static CliRequest buildRequest(String[] args, ISourceLocation manifestRoot) throws ReflectiveOperationException { + // we need to set a field that the default class doesn't set + // it's a work around around a bug in the MavenCli code + var cons = CliRequest.class.getDeclaredConstructor(String[].class, ClassWorld.class); + cons.setAccessible(true); + var result = cons.newInstance(args, null); + var manifestRootFile = new File(manifestRoot.getPath()); + setField(result, "workingDirectory", manifestRootFile.getPath()); + setField(result, "multiModuleProjectDirectory", manifestRootFile); + return result; + } + + public static Path getTempFile(String kind) throws IOException { + return Files.createTempFile("rascal-maven-" + kind + "-", ".tmp"); + } +} diff --git a/src/org/rascalmpl/library/util/PathConfig.java b/src/org/rascalmpl/library/util/PathConfig.java index 131c3e31c93..135e929bafd 100644 --- a/src/org/rascalmpl/library/util/PathConfig.java +++ b/src/org/rascalmpl/library/util/PathConfig.java @@ -1,10 +1,8 @@ package org.rascalmpl.library.util; -import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStreamReader; import java.io.StringReader; import java.io.StringWriter; import java.net.URISyntaxException; @@ -14,6 +12,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import org.rascalmpl.interpreter.Configuration; @@ -62,8 +61,6 @@ public class PathConfig { private static List defaultClassloaders; private static ISourceLocation defaultBin; - private static final String WINDOWS_ROOT_TRUSTSTORE_TYPE_DEFINITION = "-Djavax.net.ssl.trustStoreType=WINDOWS-ROOT"; - public static enum RascalConfigMode { INTERPETER, COMPILER @@ -638,97 +635,33 @@ private static ISourceLocation setTargetScheme(ISourceLocation projectLoc) { */ private static IList getPomXmlCompilerClasspath(ISourceLocation manifestRoot) { try { - ISourceLocation pomxml = URIUtil.getChildLocation(manifestRoot, "pom.xml"); - pomxml = URIResolverRegistry.getInstance().logicalToPhysical(pomxml); - manifestRoot = URIResolverRegistry.getInstance().logicalToPhysical(manifestRoot); - - if (!"file".equals(manifestRoot.getScheme())) { - return vf.list(); - } - - if (!URIResolverRegistry.getInstance().exists(pomxml)) { - return vf.list(); - } - - String mvnCommand = computeMavenCommandName(); - - installNecessaryMavenPlugins(mvnCommand); - - // Note how we try to do this "offline" using the "-o" flag - ProcessBuilder processBuilder = new ProcessBuilder(mvnCommand, - "--batch-mode", - "-o", - "dependency:build-classpath", - "-DincludeScope=compile", - trustStoreFix() - ); - - processBuilder.directory(new File(manifestRoot.getPath())); - processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home", System.getenv("JAVA_HOME"))); - - Process process = processBuilder.start(); - - try (BufferedReader processOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - return processOutputReader.lines() - .filter(line -> !line.startsWith("[")) - .filter(line -> !line.contains("-----")) - .flatMap(line -> Arrays.stream(line.split(File.pathSeparator))) - .filter(fileName -> new File(fileName).exists()) - .map(elem -> { - try { - return URIUtil.createFileLocation(elem); - } - catch (URISyntaxException e) { - return null; - } - }) - .filter(e -> e != null) - .collect(vf.listWriter()); - } + String mavenDependencyPlugin = "org.apache.maven.plugins:maven-dependency-plugin:3.8.0"; + // First, make sure that maven-dependency-plugin is downloaded when not available + Maven.runCommand(List.of(mavenDependencyPlugin + ":do-nothing"), manifestRoot); + + // Now, actually let maven build the classpath. Note that this is in offline mode as to not download any dependencies + var tempFile = Maven.getTempFile("classpath"); + var mavenOutput = Maven.runCommand(List.of("-o", mavenDependencyPlugin + ":build-classpath", "-DincludeScope=compile", "-Dmdep.outputFile=" + tempFile.toString()), manifestRoot, tempFile); + + // The classpath will be written to the temp file on a single line + return Arrays.stream(mavenOutput.get(0).split(File.pathSeparator)) + .filter(fileName -> new File(fileName).exists()) + .map(elem -> { + try { + return URIUtil.createFileLocation(elem); + } + catch (URISyntaxException e) { + return null; + } + }) + .filter(Objects::nonNull) + .collect(vf.listWriter()); } - catch (IOException e) { + catch (IOException | RuntimeException e) { return vf.list(); } } - private static boolean isWindows() { - return System.getProperty("os.name").toLowerCase().contains("win"); - } - - private static String computeMavenCommandName() { - if (System.getProperty("os.name", "generic").startsWith("Windows")) { - return "mvn.cmd"; - } - else { - return "mvn"; - } - } - - private static void installNecessaryMavenPlugins(String mvnCommand) { - try { - ProcessBuilder processBuilder = new ProcessBuilder(mvnCommand, - "-q", - "dependency:get", - "-DgroupId=org.apache.maven.plugins", - "-DartifactId=maven-dependency-plugin", - "-Dversion=2.8", - trustStoreFix()); - processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home", System.getenv("JAVA_HOME"))); - - Process process = processBuilder.start(); - if (process.waitFor() != 0) { - throw new IOException("mvn dependency:get returned non-zero"); - } - } - catch (IOException | InterruptedException e) { - System.err.println("[WARNING] Could not install exec-maven-plugin; classpath resolution may be incomplete hereafter: " + e.getMessage()); - } - } - - private static String trustStoreFix() { - return isWindows() ? WINDOWS_ROOT_TRUSTSTORE_TYPE_DEFINITION : "-Dnothing_to_see_here"; - } - public ISourceLocation getBin() { return bin; }