Skip to content

Commit 32443e3

Browse files
authored
Add all discovered modules from the classpath to compile tasks (#792)
Allows user programs to use `import module` statements without needing to write `module-info,java` files (and keep them up to date as they add vendor libraries)
1 parent a99e56f commit 32443e3

8 files changed

Lines changed: 152 additions & 14 deletions

File tree

‎src/main/java/org/wpilib/gradlerio/wpi/WPIExtension.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import org.gradle.plugins.ide.eclipse.model.ClasspathEntry;
1818
import org.gradle.plugins.ide.eclipse.model.EclipseClasspath;
1919
import org.gradle.plugins.ide.eclipse.model.EclipseModel;
20+
import org.gradle.plugins.ide.eclipse.model.Library;
2021
import org.gradle.plugins.ide.eclipse.model.SourceFolder;
2122
import org.wpilib.gradlerio.wpi.cpp.WPINativeExtension;
2223
import org.wpilib.gradlerio.wpi.java.WPIJavaExtension;
@@ -94,6 +95,19 @@ public WPIExtension(Project project) {
9495
eclipseClasspath.getFile().whenMerged(cp -> {
9596
if (cp instanceof org.gradle.plugins.ide.eclipse.model.Classpath ecp) {
9697
List<ClasspathEntry> entries = ecp.getEntries();
98+
99+
// If the team program doesn't have a module-info file (which we expect for basically every team),
100+
// the Eclipse compiler won't place any modular dependencies on the module path, which breaks
101+
// intellisense when teams use modular imports (eg from example and template projects).
102+
// So we force every modular dependency that's on the Eclipse classpath to be on the module path
103+
entries.forEach(entry -> {
104+
if (entry instanceof org.gradle.plugins.ide.eclipse.model.Library lib) {
105+
if (WPIModulesPlugin.isModuleLike(new File(lib.getPath()), project)) {
106+
lib.getEntryAttributes().put("module", true);
107+
}
108+
}
109+
});
110+
97111
// TODO make this grab the build folder dynamically
98112
SourceFolder src = new SourceFolder("build/generated/sources/annotationProcessor/java/main", null);
99113
entries.add(src);
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package org.wpilib.gradlerio.wpi;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.lang.module.ModuleFinder;
6+
import java.net.URI;
7+
import java.nio.file.Path;
8+
import java.util.List;
9+
import java.util.jar.JarFile;
10+
import java.util.stream.Collectors;
11+
import org.gradle.api.Plugin;
12+
import org.gradle.api.Project;
13+
import org.gradle.api.file.FileCollection;
14+
import org.gradle.api.tasks.compile.JavaCompile;
15+
16+
/**
17+
* Configures java compilation tasks to automatically make available every module detected on the classpath. JAR files
18+
* with an Automatic-Module-Name manifest entry will be included, but JAR files with neither a module-info entry nor a
19+
* fallback manifest entry will <i>not</i> be added to the module path.
20+
*
21+
* <p>This basically does the same thing as org.gradle.internal.jvm.JavaModuleDetector, but where we don't care if the
22+
* project is modular. Gradle, by contrast, will only move modular dependencies to the module path if inferModulePath
23+
* is on <i>and</i> the project has a module-info file. This plugin is compatible with inferModulePath and modular
24+
* projects; both Gradle and the plugin will remove modular JARs from the classpath and place them on the module path,
25+
* and since they do the same thing we always get identical --module-path arguments passed to the compiler.
26+
*/
27+
public class WPIModulesPlugin implements Plugin<Project> {
28+
@Override
29+
public void apply(Project project) {
30+
project.getTasks().withType(JavaCompile.class).configureEach(compileJava -> {
31+
FileCollection originalClasspath = compileJava.getClasspath();
32+
if (originalClasspath == null) {
33+
// Probably a custom task that hasn't had a classpath configured.
34+
// Do nothing and bail
35+
return;
36+
}
37+
38+
// Split the original classpath into modular and nonmodular dependencies. This ensures dependencies only appear
39+
// on either the classpath or module path, never both. Note that any entries added to the classpath after the
40+
// plugin is applied will remain on the classpath, even if they are modular!
41+
FileCollection modular = originalClasspath.filter(f -> isModuleLike(f, project));
42+
FileCollection nonmodular = originalClasspath.filter(f -> !isModuleLike(f, project));
43+
compileJava.setClasspath(nonmodular);
44+
45+
compileJava.getOptions().getCompilerArgumentProviders().add(() -> {
46+
if (modular.isEmpty()) {
47+
// No modular JARs - which is weird, since wpilib JARs should all be modular.
48+
// Exit early and do nothing instead of breaking the build.
49+
project.getLogger().warn(
50+
"No modular JARs were detected on the classpath for task '{}'. Are the WPILib dependencies present?",
51+
compileJava.getName());
52+
return List.of();
53+
}
54+
55+
var moduleFinder =
56+
ModuleFinder.of(modular.getFiles().stream().map(File::toPath).toArray(Path[]::new));
57+
58+
var modules = moduleFinder.findAll();
59+
60+
project.getLogger().debug("Adding modules to the compile task `{}`:", compileJava.getName());
61+
modules.forEach(mod -> {
62+
project.getLogger().debug(
63+
"Adding module {} from {}",
64+
mod.descriptor().name(),
65+
mod.location().map(URI::toString).orElse("<unknown location>"));
66+
});
67+
68+
var moduleNames =
69+
modules.stream().map(mod -> mod.descriptor().name()).collect(Collectors.joining(","));
70+
71+
// Note: Gradle's DefaultJavaCompileSpec will search for an explicit --module-path argument and duplicate it.
72+
// There doesn't seem to be a good reason for this, but it causes our module path to appear twice in the
73+
// compiler arguments. This behavior won't cause problems because the last --module-path argument overrides any
74+
// earlier ones, so the work that Gradle is doing is merely redundant rather than harmful.
75+
return List.of(
76+
"--module-path",
77+
modular.getAsPath(),
78+
"--add-modules",
79+
moduleNames
80+
);
81+
});
82+
});
83+
}
84+
85+
public static boolean isModuleLike(File file, Project project) {
86+
if (file.isDirectory()) {
87+
// Loose directories need a module-info.class entry
88+
return new File(file, "module-info.class").isFile();
89+
}
90+
91+
if (!file.getName().endsWith(".jar")) {
92+
// Given a file, but not a JAR.
93+
return false;
94+
}
95+
96+
try (var jarFile = new JarFile(file)) {
97+
var moduleInfoEntry = jarFile.getJarEntry("module-info.class");
98+
if (moduleInfoEntry != null) {
99+
// This JAR file has explicit module information; add it to the module path.
100+
// Note that this automatically handles multi-release JARs, so if a dependency has module info
101+
// at META-INF/versions/9/module-info.class instead of in the root, it will still be detected
102+
project.getLogger().debug("Found module-info.class in dependency {}", file);
103+
return true;
104+
}
105+
106+
// No explicit module information is present.
107+
// Fall back to scan for an Automatic-Module-Name manifest entry
108+
var manifest = jarFile.getManifest();
109+
var automaticName = manifest.getMainAttributes().getValue("Automatic-Module-Name");
110+
if (automaticName != null && !automaticName.isEmpty()) {
111+
project.getLogger().debug(
112+
"Found Automatic-Module-Name manifest entry '{}' in dependency {}",
113+
automaticName, file);
114+
return true;
115+
}
116+
117+
// No explicit module-info and no Automatic-Module-Name manifest entry.
118+
// This is not a modular dependency and will left on the classpath.
119+
project.getLogger().debug(
120+
"Did not find any module information in dependency {} - it will be left on the classpath", file);
121+
return false;
122+
} catch (IOException e) {
123+
throw new RuntimeException("Unable to examine classpath JAR " + file, e);
124+
}
125+
}
126+
}

‎src/main/java/org/wpilib/gradlerio/wpi/WPIPlugin.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public void apply(Project project) {
4040

4141
project.getPluginManager().apply(WPIToolsPlugin.class);
4242
project.getPluginManager().apply(WPIDependenciesPlugin.class);
43+
project.getPluginManager().apply(WPIModulesPlugin.class);
4344

4445
project.getTasks().register("wpiVersions", task -> {
4546
task.setGroup("GradleRIO");

‎src/main/java/org/wpilib/gradlerio/wpi/java/WPIJavaDepsExtension.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ public WPIJavaDepsExtension(WPIVersionsExtension versions, ProviderFactory provi
4444
this.providers = providers;
4545
this.versions = versions;
4646

47+
createJavaDependencies("org.wpilib.allwpilib", "allwpilib-java", versions.getWpilibVersion());
4748
createJavaDependencies("org.wpilib.wpilibj", "wpilibj-java", versions.getWpilibVersion());
4849
createJavaDependencies("org.wpilib.wpimath", "wpimath-java", versions.getWpilibVersion());
4950
createJavaDependencies("org.wpilib.ntcore", "ntcore-java", versions.getWpilibVersion());
@@ -61,7 +62,7 @@ public WPIJavaDepsExtension(WPIVersionsExtension versions, ProviderFactory provi
6162
createJavaDependencies("org.wpilib", "annotations-java", versions.getWpilibVersion());
6263

6364
createJavaDependencies("io.avaje", "avaje-jsonb", versions.getAvajeVersion());
64-
createJavaDependencies("org.ejml", "ejml-simple", versions.getEjmlVersion());
65+
createJavaDependencies("org.ejml", "ejml-java9module", versions.getEjmlVersion());
6566
createJavaDependencies("us.hebi.quickbuf", "quickbuf-runtime", versions.getQuickbufVersion());
6667
}
6768

‎testing/java/src/main/java/first/team0000/robot/Main.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
package first.team0000.robot;
99

10-
import org.wpilib.framework.RobotBase;
10+
import module wpilib;
1111

1212
/**
1313
* Do NOT add any static variables to this class, or any initialization at all.

‎testing/java/src/main/java/first/team0000/robot/Robot.java‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
package first.team0000.robot;
22

3-
import org.wpilib.drive.DifferentialDrive;
4-
import org.wpilib.drivers.motor.PWMSparkMax;
5-
import org.wpilib.driverstation.Gamepad;
6-
import org.wpilib.framework.TimedRobot;
7-
import org.wpilib.system.Timer;
8-
3+
import module wpilib;
4+
import module wpilib.drivers;
95

106
/**
117
* The methods in this class are called automatically corresponding to each mode, as described in

‎testing/java/vendordeps/CameraServer.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
{
1111
"groupId": "org.wpilib.thirdparty.opencv",
1212
"artifactId": "opencv-java",
13-
"version": "2027-4.13.0-3"
13+
"version": "2027-4.13.0-4"
1414
},
1515
{
1616
"groupId": "org.wpilib.cscore",
@@ -27,7 +27,7 @@
2727
{
2828
"groupId": "org.wpilib.thirdparty.opencv",
2929
"artifactId": "opencv-cpp",
30-
"version": "2027-4.13.0-3",
30+
"version": "2027-4.13.0-4",
3131
"skipInvalidPlatforms": true,
3232
"isJar": false,
3333
"validPlatforms": [
@@ -59,7 +59,7 @@
5959
{
6060
"groupId": "org.wpilib.thirdparty.opencv",
6161
"artifactId": "opencv-cpp",
62-
"version": "2027-4.13.0-3",
62+
"version": "2027-4.13.0-4",
6363
"libName": "opencv",
6464
"headerClassifier": "headers",
6565
"sourcesClassifier": "sources",

‎testing/kotlin/vendordeps/CameraServer.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
{
1111
"groupId": "org.wpilib.thirdparty.opencv",
1212
"artifactId": "opencv-java",
13-
"version": "2027-4.13.0-3"
13+
"version": "2027-4.13.0-4"
1414
},
1515
{
1616
"groupId": "org.wpilib.cscore",
@@ -27,7 +27,7 @@
2727
{
2828
"groupId": "org.wpilib.thirdparty.opencv",
2929
"artifactId": "opencv-cpp",
30-
"version": "2027-4.13.0-3",
30+
"version": "2027-4.13.0-4",
3131
"skipInvalidPlatforms": true,
3232
"isJar": false,
3333
"validPlatforms": [
@@ -59,7 +59,7 @@
5959
{
6060
"groupId": "org.wpilib.thirdparty.opencv",
6161
"artifactId": "opencv-cpp",
62-
"version": "2027-4.13.0-3",
62+
"version": "2027-4.13.0-4",
6363
"libName": "opencv",
6464
"headerClassifier": "headers",
6565
"sourcesClassifier": "sources",

0 commit comments

Comments
 (0)