Skip to content

Commit c5507cc

Browse files
committed
Avoid duplication og Gradle plugin logic.
1 parent d11652d commit c5507cc

File tree

2 files changed

+149
-199
lines changed

2 files changed

+149
-199
lines changed

byte-buddy-gradle-plugin/android-plugin/src/main/java/net/bytebuddy/build/gradle/android/ByteBuddyLocalClassesEnhancerTask.java

Lines changed: 49 additions & 138 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,10 @@
1919
import net.bytebuddy.ByteBuddy;
2020
import net.bytebuddy.ClassFileVersion;
2121
import net.bytebuddy.build.AndroidDescriptor;
22-
import net.bytebuddy.build.BuildLogger;
2322
import net.bytebuddy.build.EntryPoint;
2423
import net.bytebuddy.build.Plugin;
2524
import net.bytebuddy.description.type.TypeDescription;
2625
import net.bytebuddy.dynamic.ClassFileLocator;
27-
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;
2826
import net.bytebuddy.utility.QueueFactory;
2927
import net.bytebuddy.utility.nullability.MaybeNull;
3028
import org.gradle.api.Action;
@@ -38,6 +36,7 @@
3836
import org.gradle.api.tasks.*;
3937

4038
import java.io.*;
39+
import java.lang.reflect.InvocationTargetException;
4140
import java.net.MalformedURLException;
4241
import java.net.URL;
4342
import java.net.URLClassLoader;
@@ -205,107 +204,64 @@ public void execute() throws IOException {
205204
for (RegularFile jarFile : getInputJars().get()) {
206205
sources.add(new Plugin.Engine.Source.ForJarFile(jarFile.getAsFile()));
207206
}
208-
Plugin.Engine.Summary summary;
207+
ClassFileVersion classFileVersion = ClassFileVersion.ofJavaVersionString(getJavaTargetCompatibilityVersion().get().toString());
208+
AndroidDescriptor androidDescriptor = DefaultAndroidDescriptor.ofClassPath(localClasspath);
209209
ClassLoader classLoader = new URLClassLoader(
210210
toUrls(getByteBuddyClasspath().getFiles()),
211211
new URLClassLoader(toUrls(getAndroidBootClasspath().getFiles()), ByteBuddy.class.getClassLoader()));
212212
try {
213-
if (getDiscovery().get().isDiscover(transformations)) {
214-
Set<String> undiscoverable = new HashSet<String>();
215-
if (getDiscovery().get().isRecordConfiguration()) {
216-
for (Transformation transformation : transformations) {
217-
undiscoverable.add(transformation.toPluginName());
218-
}
219-
}
220-
for (String name : Plugin.Engine.Default.scan(classLoader)) {
221-
if (undiscoverable.add(name)) {
222-
try {
223-
@SuppressWarnings("unchecked")
224-
Class<? extends Plugin> plugin = (Class<? extends Plugin>) Class.forName(name, false, classLoader);
225-
Transformation transformation = new Transformation();
226-
transformation.setPlugin(plugin);
227-
transformations.add(transformation);
228-
} catch (ClassNotFoundException exception) {
229-
throw new IllegalStateException("Discovered plugin is not available: " + name, exception);
230-
}
231-
getLogger().debug("Registered discovered plugin: {}", name);
232-
} else {
233-
getLogger().info("Skipping discovered plugin {} which was previously discovered or registered", name);
234-
}
235-
}
236-
}
237-
if (transformations.isEmpty()) {
238-
getLogger().warn("No transformations are specified or discovered. Application will be non-operational.");
213+
Class.forName("net.bytebuddy.build.gradle.AbstractByteBuddyTask").getMethod("apply",
214+
Logger.class,
215+
ClassLoader.class,
216+
List.class,
217+
Class.forName("net.bytebuddy.build.gradle.Discovery"),
218+
ClassFileLocator.class,
219+
Iterable.class,
220+
Iterable.class,
221+
EntryPoint.class,
222+
ClassFileVersion.class,
223+
Plugin.Factory.UsingReflection.ArgumentResolver.class,
224+
String.class,
225+
int.class,
226+
boolean.class,
227+
boolean.class,
228+
boolean.class,
229+
boolean.class,
230+
Plugin.Engine.Source.class,
231+
Plugin.Engine.Target.class).invoke(null,
232+
getLogger(),
233+
classLoader,
234+
transformations,
235+
getDiscovery().get(),
236+
ClassFileLocator.ForClassLoader.of(ByteBuddy.class.getClassLoader()),
237+
getAndroidBootClasspath().plus(getByteBuddyClasspath()).getFiles(),
238+
Collections.emptyList(), // TODO
239+
getEntryPoint().get(),
240+
classFileVersion,
241+
Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(AndroidDescriptor.class, androidDescriptor),
242+
getSuffix().get(),
243+
getThreads().get(),
244+
getExtendedParsing().get(),
245+
getFailFast().get(),
246+
getFailOnLiveInitializer().get(),
247+
getWarnOnEmptyTypeSet().get(),
248+
new Plugin.Engine.Source.Compound(sources),
249+
new TargetForAndroidAppJarFile(getOutputFile().get().getAsFile()));
250+
} catch (InvocationTargetException exception) {
251+
Throwable cause = exception.getCause();
252+
if (cause instanceof IOException) {
253+
throw (IOException) cause;
254+
} else if (cause instanceof RuntimeException){
255+
throw (RuntimeException) cause;
239256
} else {
240-
getLogger().debug("{} plugins are being applied via configuration and discovery", transformations.size());
241-
}
242-
List<Plugin.Factory> factories = new ArrayList<Plugin.Factory>(transformations.size());
243-
BuildLogger buildLogger;
244-
try {
245-
buildLogger = (BuildLogger) Class.forName("net.bytebuddy.build.gradle.GradleBuildLogger")
246-
.getConstructor(Logger.class)
247-
.newInstance(getLogger());
248-
} catch (Exception exception) {
249-
throw new GradleException("Failed to resolve Gradle build logger", exception);
250-
}
251-
AndroidDescriptor androidDescriptor = DefaultAndroidDescriptor.ofClassPath(localClasspath);
252-
for (Transformation transformation : transformations) {
253-
try {
254-
factories.add(new Plugin.Factory.UsingReflection(transformation.toPlugin(classLoader))
255-
.with(transformation.makeArgumentResolvers())
256-
.with(Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(AndroidDescriptor.class, androidDescriptor))
257-
.with(Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(Logger.class, getLogger()))
258-
.with(Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(org.slf4j.Logger.class, getLogger()))
259-
.with(Plugin.Factory.UsingReflection.ArgumentResolver.ForType.of(BuildLogger.class, buildLogger)));
260-
getLogger().info("Resolved plugin: {}", transformation.toPluginName());
261-
} catch (Throwable throwable) {
262-
throw new IllegalStateException("Cannot resolve plugin: " + transformation.toPluginName(), throwable);
263-
}
264-
}
265-
ClassFileVersion classFileVersion = ClassFileVersion.ofJavaVersionString(getJavaTargetCompatibilityVersion().get().toString());
266-
List<ClassFileLocator> classFileLocators = new ArrayList<ClassFileLocator>();
267-
for (File file : getAndroidBootClasspath().plus(getByteBuddyClasspath()).getFiles()) {
268-
classFileLocators.add(file.isFile()
269-
? ClassFileLocator.ForJarFile.of(file)
270-
: new ClassFileLocator.ForFolder(file));
271-
}
272-
classFileLocators.add(ClassFileLocator.ForClassLoader.of(ByteBuddy.class.getClassLoader()));
273-
ClassFileLocator classFileLocator = new ClassFileLocator.Compound(classFileLocators);
274-
try {
275-
summary = Plugin.Engine.Default.of(getEntryPoint().get(), classFileVersion, getSuffix().get().length() == 0
276-
? MethodNameTransformer.Suffixing.withRandomSuffix()
277-
: new MethodNameTransformer.Suffixing(getSuffix().get()))
278-
.with(getExtendedParsing().get()
279-
? Plugin.Engine.PoolStrategy.Default.EXTENDED
280-
: Plugin.Engine.PoolStrategy.Default.FAST)
281-
.with(classFileLocator)
282-
.with(new TransformationLogger(getLogger()))
283-
.withErrorHandlers(Plugin.Engine.ErrorHandler.Enforcing.ALL_TYPES_RESOLVED, getFailOnLiveInitializer().get()
284-
? Plugin.Engine.ErrorHandler.Enforcing.NO_LIVE_INITIALIZERS
285-
: Plugin.Engine.Listener.NoOp.INSTANCE, getFailFast().get()
286-
? Plugin.Engine.ErrorHandler.Failing.FAIL_FAST
287-
: Plugin.Engine.ErrorHandler.Failing.FAIL_LAST)
288-
.with(getThreads().get() == 0
289-
? Plugin.Engine.Dispatcher.ForSerialTransformation.Factory.INSTANCE
290-
: new Plugin.Engine.Dispatcher.ForParallelTransformation.WithThrowawayExecutorService.Factory(getThreads().get()))
291-
.apply(new Plugin.Engine.Source.Compound(sources), new TargetForAndroidAppJarFile(getOutputFile().get().getAsFile()), factories);
292-
} finally {
293-
classFileLocator.close();
257+
throw new GradleException("Unexpected transformation error", exception);
294258
}
259+
} catch (Throwable throwable) {
260+
throw new GradleException("Unexpected transformation error", throwable);
295261
} finally {
296262
if (classLoader instanceof Closeable) {
297263
((Closeable) classLoader).close();
298264
}
299-
if (classLoader.getParent() instanceof Closeable) {
300-
((Closeable) classLoader.getParent()).close();
301-
}
302-
}
303-
if (!summary.getFailed().isEmpty()) {
304-
throw new IllegalStateException(summary.getFailed() + " type transformation(s) have failed");
305-
} else if (getWarnOnEmptyTypeSet().get() && summary.getTransformed().isEmpty()) {
306-
getLogger().warn("No types were transformed during plugin execution");
307-
} else {
308-
getLogger().info("Transformed {} type(s)", summary.getTransformed().size());
309265
}
310266
}
311267

@@ -490,49 +446,4 @@ public void retain(Plugin.Engine.Source.Element element) throws IOException {
490446
}
491447
}
492448
}
493-
494-
/**
495-
* A {@link net.bytebuddy.build.Plugin.Engine.Listener} that logs several relevant events during the build.
496-
*/
497-
protected static class TransformationLogger extends Plugin.Engine.Listener.Adapter {
498-
499-
/**
500-
* The logger to delegate to.
501-
*/
502-
private final Logger logger;
503-
504-
/**
505-
* Creates a new transformation logger.
506-
*
507-
* @param logger The logger to delegate to.
508-
*/
509-
protected TransformationLogger(Logger logger) {
510-
this.logger = logger;
511-
}
512-
513-
@Override
514-
public void onTransformation(TypeDescription typeDescription, List<Plugin> plugins) {
515-
logger.debug("Transformed {} using {}", typeDescription, plugins);
516-
}
517-
518-
@Override
519-
public void onError(TypeDescription typeDescription, Plugin plugin, Throwable throwable) {
520-
logger.warn("Failed to transform {} using {}", typeDescription, plugin, throwable);
521-
}
522-
523-
@Override
524-
public void onError(Map<TypeDescription, List<Throwable>> throwables) {
525-
logger.warn("Failed to transform {} types", throwables.size());
526-
}
527-
528-
@Override
529-
public void onError(Plugin plugin, Throwable throwable) {
530-
logger.error("Failed to close {}", plugin, throwable);
531-
}
532-
533-
@Override
534-
public void onLiveInitializer(TypeDescription typeDescription, TypeDescription definingType) {
535-
logger.debug("Discovered live initializer for {} as a result of transforming {}", definingType, typeDescription);
536-
}
537-
}
538449
}

0 commit comments

Comments
 (0)