Skip to content

Commit 1269a86

Browse files
authored
Remove plugin-init.groovy in resources and compile the plugin code with groovyc (#221)
1 parent 734fec9 commit 1269a86

File tree

6 files changed

+118
-151
lines changed

6 files changed

+118
-151
lines changed

build.xml

+16-2
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,13 @@
220220
<equals arg1="${ivy.version}" arg2="${ivy.install.version}"/>
221221
</condition>
222222
<echo level="warn" taskname="check-ivy" message="${ivy.version-message}"/>
223-
<ivy:cachepath pathid="path.main-build" conf="build" log="${ivy.logging}"/>
223+
<ivy:cachepath pathid="-path.main-build1" conf="build" log="${ivy.logging}"/>
224+
<ivy:cachepath pathid="-path.main-build2" conf="buildgradle" log="${ivy.logging}"/>
225+
<path id="path.main-build">
226+
<!-- order is important as the gradle JAR contains lots of outdated stuff, so should be last! -->
227+
<path refid="-path.main-build1"/>
228+
<path refid="-path.main-build2"/>
229+
</path>
224230
<ivy:cachepath pathid="path.main-bundle" conf="bundle" log="${ivy.logging}"/>
225231
<ivy:cachepath pathid="path.test" conf="test" log="${ivy.logging}"/>
226232
<ivy:cachepath pathid="path.jarjar" conf="jarjar" log="${ivy.logging}"/>
@@ -255,6 +261,7 @@
255261
<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpathref="path.jarjar"/>
256262
<taskdef uri="antlib:org.apache.maven.artifact.ant" classpathref="path.tasks"/>
257263
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="path.tasks"/>
264+
<taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpathref="path.tasks"/>
258265
<typedef uri="antlib:org.apache.rat.anttasks" classpathref="path.tasks"/>
259266
<artifact:remoteRepository id="mvn.maven-central.backup" url="${ivy.maven-central.backup}"/>
260267
<!-- Make sure we downloaded Maven, so artifact:mvn can bootstrap itsself -->
@@ -282,8 +289,15 @@
282289
</sequential>
283290
</macrodef>
284291

285-
<target name="compile" depends="-init" description="Compile">
292+
<target name="compile" depends="-install-tasks" description="Compile main">
286293
<compile module="main" classpathref="path.main-build"/>
294+
<groovyc srcdir="src/main/groovy" destdir="build/main"
295+
indy="true" targetBytecode="${jdk.version}" encoding="${build.encoding}">
296+
<classpath>
297+
<path refid="path.main-build"/>
298+
<pathelement path="build/main"/>
299+
</classpath>
300+
</groovyc>
287301
</target>
288302

289303
<target name="compile-tools" depends="compile" description="Compile tools">

ivy.xml

+4-3
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@
2222
]>
2323
<ivy-module version="2.0">
2424
<info organisation="de.thetaphi" module="forbiddenapis"/>
25-
<configurations defaultconfmapping="build-&gt;*;bundle-&gt;*;test-&gt;*;buildtools-&gt;*;jarjar-&gt;*">
25+
<configurations defaultconfmapping="build-&gt;*;buildgradle-&gt;*;bundle-&gt;*;test-&gt;*;buildtools-&gt;*;jarjar-&gt;*">
2626
<conf name="build" transitive="false" visibility="private" />
27+
<conf name="buildgradle" transitive="false" visibility="private" />
2728
<conf name="bundle" transitive="false" visibility="private" />
2829
<conf name="test" transitive="false" visibility="private" />
2930
<conf name="buildtools" transitive="false" visibility="private" />
@@ -35,10 +36,10 @@
3536
<dependency org="org.apache.maven" name="maven-plugin-api" rev="&maven.version;" conf="build"/>
3637
<dependency org="org.apache.maven" name="maven-artifact" rev="&maven.version;" conf="build"/>
3738
<dependency org="org.apache.maven.plugin-tools" name="maven-plugin-annotations" rev="3.4" conf="build"/>
38-
<dependency org="dev.gradleplugins" name="gradle-api" rev="&gradle.version;" conf="build"/>
3939
<dependency org="org.slf4j" name="slf4j-api" rev="1.7.7" conf="build"/>
40+
<dependency org="dev.gradleplugins" name="gradle-api" rev="&gradle.version;" conf="buildgradle"/>
4041
<!-- Gradle also needs Groovy, but we need it as build tool, too: -->
41-
<dependency org="org.codehaus.groovy" name="groovy-all" rev="2.4.17" conf="build,buildtools"/>
42+
<dependency org="org.codehaus.groovy" name="groovy-all" rev="2.4.21" conf="build,buildtools"/>
4243
<!-- ASM minimal (latest version) required: -->
4344
<dependency org="org.ow2.asm" name="asm" rev="&asm.version;" conf="build,bundle,buildtools"/>
4445
<dependency org="org.ow2.asm" name="asm-commons" rev="&asm.version;" conf="build,bundle,buildtools"/>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*
2+
* (C) Copyright Uwe Schindler (Generics Policeman) and others.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package de.thetaphi.forbiddenapis.gradle;
18+
19+
import org.gradle.api.GradleException;
20+
import org.gradle.api.Project;
21+
import org.gradle.api.file.ConfigurableFileCollection;
22+
import org.gradle.api.plugins.JavaBasePlugin;
23+
import org.gradle.util.GradleVersion;
24+
25+
/**
26+
* Forbiddenapis Gradle Plugin (requires at least Gradle v3.2)
27+
* @since 2.0
28+
*/
29+
public class ForbiddenApisPlugin extends ForbiddenApisPluginBase {
30+
31+
@Override
32+
public void apply(Project project) {
33+
if (GradleVersion.current().compareTo(MIN_GRADLE_VERSION) < 0) {
34+
throw new GradleException("Forbiddenapis plugin requires at least " + MIN_GRADLE_VERSION + ", running version is " + GradleVersion.current());
35+
}
36+
37+
project.plugins.apply(JavaBasePlugin.class);
38+
39+
// create Extension for defaults:
40+
def extension = project.extensions.create(FORBIDDEN_APIS_EXTENSION_NAME, CheckForbiddenApisExtension.class, project);
41+
42+
// Create a convenience task for all checks (this does not conflict with extension, as it has higher priority in DSL):
43+
def forbiddenTask = TASK_AVOIDANCE_AVAILABLE ? project.tasks.register(FORBIDDEN_APIS_TASK_NAME) : project.tasks.create(FORBIDDEN_APIS_TASK_NAME)
44+
forbiddenTask.configure {
45+
description = "Runs forbidden-apis checks.";
46+
group = JavaBasePlugin.VERIFICATION_GROUP;
47+
}
48+
49+
// Gradle is buggy with it's JavaVersion enum: We use majorVersion property before Java 11 (6,7,8,9,10) and for later we use toString() to be future-proof:
50+
Closure targetCompatibilityGetter = { (project.targetCompatibility?.hasProperty('java11Compatible') && project.targetCompatibility?.java11Compatible) ?
51+
project.targetCompatibility.toString() : project.targetCompatibility?.majorVersion };
52+
53+
// Define our tasks (one for each SourceSet):
54+
project.sourceSets.all{ sourceSet ->
55+
String sourceSetTaskName = sourceSet.getTaskName(FORBIDDEN_APIS_TASK_NAME, null);
56+
def sourceSetTask = TASK_AVOIDANCE_AVAILABLE ? project.tasks.register(sourceSetTaskName, CheckForbiddenApis.class) :
57+
project.tasks.create(sourceSetTaskName, CheckForbiddenApis.class);
58+
def templateClassesDirs = project.files();
59+
def templateClasspath = project.files();
60+
sourceSetTask.configure {
61+
description = "Runs forbidden-apis checks on '${sourceSet.name}' classes.";
62+
dependsOn(sourceSet.output);
63+
outputs.upToDateWhen { true }
64+
def taskData = internalTaskData()
65+
conventionMapping.with{
66+
FORBIDDEN_APIS_EXTENSION_PROPS.each{ key ->
67+
map(key, {
68+
def item = taskData[key]
69+
if (item instanceof ConfigurableFileCollection) {
70+
return item.from(extension[key])
71+
} else if (item instanceof Collection) {
72+
item.addAll(extension[key])
73+
return item
74+
}
75+
return extension[key]
76+
})
77+
}
78+
classesDirs = { templateClassesDirs.from(sourceSet.output.hasProperty('classesDirs') ? sourceSet.output.classesDirs : sourceSet.output.classesDir) }
79+
classpath = { templateClasspath.from(sourceSet.compileClasspath) }
80+
targetCompatibility = targetCompatibilityGetter
81+
}
82+
}
83+
forbiddenTask.configure {
84+
dependsOn(sourceSetTask)
85+
}
86+
}
87+
88+
// Add our task as dependency to chain
89+
def checkTask = TASK_AVOIDANCE_AVAILABLE ? project.tasks.named(JavaBasePlugin.CHECK_TASK_NAME) : project.tasks.getByName(JavaBasePlugin.CHECK_TASK_NAME);
90+
checkTask.configure { it.dependsOn(forbiddenTask) };
91+
}
92+
93+
}

src/main/java/de/thetaphi/forbiddenapis/gradle/CheckForbiddenApisExtension.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,6 @@ public CheckForbiddenApisExtension(Project project) {
4747
failOnUnresolvableSignatures = true,
4848
ignoreFailures = false,
4949
ignoreSignaturesOfMissingClasses = false,
50-
disableClassloadingCache = ForbiddenApisPlugin.DEFAULT_DISABLE_CLASSLOADING_CACHE;
50+
disableClassloadingCache = ForbiddenApisPluginBase.DEFAULT_DISABLE_CLASSLOADING_CACHE;
5151

5252
}

src/main/java/de/thetaphi/forbiddenapis/gradle/ForbiddenApisPlugin.java renamed to src/main/java/de/thetaphi/forbiddenapis/gradle/ForbiddenApisPluginBase.java

+4-68
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,21 @@
1616

1717
package de.thetaphi.forbiddenapis.gradle;
1818

19-
import groovy.lang.GroovyClassLoader;
20-
import groovy.lang.GroovyCodeSource;
21-
import groovy.util.DelegatingScript;
22-
2319
import java.lang.reflect.Field;
2420
import java.lang.reflect.Modifier;
25-
import java.net.URL;
26-
import java.nio.charset.StandardCharsets;
27-
import java.security.AccessController;
28-
import java.security.PrivilegedAction;
2921
import java.util.ArrayList;
3022
import java.util.Collections;
3123
import java.util.List;
3224

33-
import org.codehaus.groovy.control.CompilerConfiguration;
34-
import org.codehaus.groovy.control.customizers.ImportCustomizer;
35-
import org.gradle.api.GradleException;
3625
import org.gradle.api.Plugin;
3726
import org.gradle.api.Project;
3827
import org.gradle.api.logging.Logger;
3928
import org.gradle.api.logging.Logging;
4029
import org.gradle.util.GradleVersion;
4130

42-
/**
43-
* Forbiddenapis Gradle Plugin (requires at least Gradle v3.2)
44-
* @since 2.0
45-
*/
46-
public class ForbiddenApisPlugin implements Plugin<Project> {
31+
abstract class ForbiddenApisPluginBase implements Plugin<Project> {
4732

48-
private static final Logger LOG = Logging.getLogger(ForbiddenApisPlugin.class);
33+
private static final Logger LOG = Logging.getLogger(ForbiddenApisPluginBase.class);
4934

5035
/** Name of the base task that depends on one for every SourceSet. */
5136
public static final String FORBIDDEN_APIS_TASK_NAME = "forbiddenApis";
@@ -69,45 +54,12 @@ public class ForbiddenApisPlugin implements Plugin<Project> {
6954
/** True, if this version of Gradle supports task avoidance API (&gt;=v4.9). */
7055
public static final boolean TASK_AVOIDANCE_AVAILABLE = GradleVersion.current().compareTo(GradleVersion.version("4.9")) >= 0;
7156

72-
/** All properties that our ForbiddenApisExtension provides. Used by plugin init script to create convention mapping. */
73-
public static final List<String> FORBIDDEN_APIS_EXTENSION_PROPS = determineExtensionProps();
57+
/** All properties that our ForbiddenApisExtension provides. Used to create convention mapping. */
58+
protected static final List<String> FORBIDDEN_APIS_EXTENSION_PROPS = determineExtensionProps();
7459

7560
/** Java Package that contains the Gradle Daemon (needed to detect it on startup). */
7661
private static final String GRADLE_DAEMON_PACKAGE = "org.gradle.launcher.daemon.";
7762

78-
/** Resource with Groovy script that initializes the plugin. */
79-
private static final String PLUGIN_INIT_SCRIPT = "plugin-init.groovy";
80-
81-
/** Compiled class instance of the plugin init script, an instance is executed per {@link #apply(Project)} */
82-
private static final Class<? extends DelegatingScript> COMPILED_SCRIPT = loadScript();
83-
84-
private static Class<? extends DelegatingScript> loadScript() {
85-
final ImportCustomizer importCustomizer = new ImportCustomizer().addStarImports(ForbiddenApisPlugin.class.getPackage().getName());
86-
final CompilerConfiguration configuration = new CompilerConfiguration().addCompilationCustomizers(importCustomizer);
87-
configuration.setScriptBaseClass(DelegatingScript.class.getName());
88-
configuration.setSourceEncoding(StandardCharsets.UTF_8.name());
89-
final URL scriptUrl = ForbiddenApisPlugin.class.getResource(PLUGIN_INIT_SCRIPT);
90-
if (scriptUrl == null) {
91-
throw new RuntimeException("Cannot find resource with script: " + PLUGIN_INIT_SCRIPT);
92-
}
93-
return AccessController.doPrivileged(new PrivilegedAction<Class<? extends DelegatingScript>>() {
94-
@Override
95-
public Class<? extends DelegatingScript> run() {
96-
try {
97-
// We don't close the classloader, as we may need it later when loading other classes from inside script:
98-
@SuppressWarnings("resource") final GroovyClassLoader loader =
99-
new GroovyClassLoader(ForbiddenApisPlugin.class.getClassLoader(), configuration);
100-
final GroovyCodeSource csrc = new GroovyCodeSource(scriptUrl);
101-
@SuppressWarnings("unchecked") final Class<? extends DelegatingScript> clazz =
102-
loader.parseClass(csrc, false).asSubclass(DelegatingScript.class);
103-
return clazz;
104-
} catch (Exception e) {
105-
throw new RuntimeException("Cannot compile Groovy script: " + PLUGIN_INIT_SCRIPT, e);
106-
}
107-
}
108-
});
109-
}
110-
11163
private static List<String> determineExtensionProps() {
11264
final List<String> props = new ArrayList<>();
11365
for (final Field f : CheckForbiddenApisExtension.class.getDeclaredFields()) {
@@ -140,20 +92,4 @@ private static boolean detectAndLogGradleDaemon() {
14092
return daemon;
14193
}
14294

143-
@Override
144-
public void apply(Project project) {
145-
if (GradleVersion.current().compareTo(MIN_GRADLE_VERSION) < 0) {
146-
throw new GradleException("Forbiddenapis plugin requires at least " + MIN_GRADLE_VERSION + ", running version is " + GradleVersion.current());
147-
}
148-
final DelegatingScript script;
149-
try {
150-
script = COMPILED_SCRIPT.newInstance();
151-
} catch (Exception e) {
152-
throw new GradleException("Cannot instantiate Groovy script to apply forbiddenapis plugin.", e);
153-
}
154-
script.setDelegate(this);
155-
script.setProperty("project", project);
156-
script.run();
157-
}
158-
15995
}

src/main/resources/de/thetaphi/forbiddenapis/gradle/plugin-init.groovy

-77
This file was deleted.

0 commit comments

Comments
 (0)