22
22
import groovy .util .DelegatingScript ;
23
23
24
24
import java .net .URL ;
25
- import java .util .Collections ;
26
25
27
26
import org .codehaus .groovy .control .CompilerConfiguration ;
28
27
import org .codehaus .groovy .control .customizers .ImportCustomizer ;
29
28
import org .gradle .api .Plugin ;
30
29
import org .gradle .api .Project ;
31
- import org .gradle .api .plugins .PluginInstantiationException ;
32
30
33
31
/**
34
32
* Forbiddenapis Gradle Plugin (requires at least Gradle 2.3)
@@ -45,22 +43,29 @@ public class ForbiddenApisPlugin implements Plugin<Project> {
45
43
/** Name of the extension to define defaults for all tasks of this module. */
46
44
public static final String FORBIDDEN_APIS_EXTENSION_NAME = "forbiddenApis" ;
47
45
48
- @ Override
49
- public void apply ( final Project project ) {
46
+ private static final DelegatingScript compiledScript ;
47
+ static {
50
48
final ImportCustomizer importCustomizer = new ImportCustomizer ().addStarImports (ForbiddenApisPlugin .class .getPackage ().getName ());
51
49
final CompilerConfiguration configuration = new CompilerConfiguration ().addCompilationCustomizers (importCustomizer );
52
50
configuration .setScriptBaseClass (DelegatingScript .class .getName ());
53
51
configuration .setSourceEncoding ("UTF-8" );
54
- final Binding binding = new Binding (Collections .singletonMap ("project" , project ));
55
- final GroovyShell shell = new GroovyShell (ForbiddenApisPlugin .class .getClassLoader (), binding , configuration );
52
+ final GroovyShell shell = new GroovyShell (ForbiddenApisPlugin .class .getClassLoader (), new Binding (), configuration );
56
53
final URL scriptUrl = ForbiddenApisPlugin .class .getResource (PLUGIN_INIT_SCRIPT );
57
54
if (scriptUrl == null ) {
58
- throw new PluginInstantiationException ("Cannot find resource with script: " + PLUGIN_INIT_SCRIPT );
55
+ throw new RuntimeException ("Cannot find resource with script: " + PLUGIN_INIT_SCRIPT );
59
56
}
60
57
final GroovyCodeSource csrc = new GroovyCodeSource (scriptUrl );
61
- final DelegatingScript script = (DelegatingScript ) shell .parse (csrc );
62
- script .setDelegate (this );
63
- script .run ();
58
+ compiledScript = (DelegatingScript ) shell .parse (csrc );
59
+ }
60
+
61
+ @ Override
62
+ public void apply (Project project ) {
63
+ synchronized (compiledScript ) {
64
+ compiledScript .setDelegate (this );
65
+ compiledScript .setProperty ("project" , project );
66
+ compiledScript .run ();
67
+ compiledScript .setProperty ("project" , null ); // free resources
68
+ }
64
69
}
65
70
66
71
}
0 commit comments