|
| 1 | +package datadog.gradle.plugin.instrument |
| 2 | + |
| 3 | +import java.nio.file.Path |
| 4 | +import java.util.concurrent.ConcurrentHashMap |
| 5 | +import javax.inject.Inject |
| 6 | +import org.gradle.api.file.FileSystemOperations |
| 7 | +import org.gradle.api.model.ObjectFactory |
| 8 | +import org.gradle.workers.WorkAction |
| 9 | + |
| 10 | +abstract class InstrumentAction implements WorkAction<InstrumentWorkParameters> { |
| 11 | + private static final Object lock = new Object() |
| 12 | + private static final Map<String, ClassLoader> classLoaderCache = new ConcurrentHashMap<>() |
| 13 | + private static volatile long lastBuildStamp |
| 14 | + |
| 15 | + @Inject |
| 16 | + public abstract FileSystemOperations getFileSystemOperations(); |
| 17 | + |
| 18 | + @Inject |
| 19 | + public abstract ObjectFactory getObjects(); |
| 20 | + |
| 21 | + @Override |
| 22 | + void execute() { |
| 23 | + String[] plugins = parameters.getPlugins().get() as String[] |
| 24 | + String classLoaderKey = plugins.join(':') |
| 25 | + |
| 26 | + // reset shared class-loaders each time a new build starts |
| 27 | + long buildStamp = parameters.buildStartedTime.get() |
| 28 | + ClassLoader pluginCL = classLoaderCache.get(classLoaderKey) |
| 29 | + if (lastBuildStamp < buildStamp || !pluginCL) { |
| 30 | + synchronized (lock) { |
| 31 | + pluginCL = classLoaderCache.get(classLoaderKey) |
| 32 | + if (lastBuildStamp < buildStamp || !pluginCL) { |
| 33 | + pluginCL = createClassLoader(parameters.pluginClassPath) |
| 34 | + classLoaderCache.put(classLoaderKey, pluginCL) |
| 35 | + lastBuildStamp = buildStamp |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + Path classesDirectory = parameters.compilerOutputDirectory.get().asFile.toPath() |
| 40 | + Path tmpUninstrumentedDir = parameters.tmpDirectory.get().asFile.toPath() |
| 41 | + |
| 42 | + // Original classes will be replaced by post-processed ones |
| 43 | + fileSystemOperations.sync { |
| 44 | + from(classesDirectory) |
| 45 | + into(tmpUninstrumentedDir) |
| 46 | + } |
| 47 | + fileSystemOperations.delete { |
| 48 | + delete(objects.fileTree().from(classesDirectory)) |
| 49 | + } |
| 50 | + |
| 51 | + ClassLoader instrumentingCL = createClassLoader(parameters.instrumentingClassPath, pluginCL) |
| 52 | + InstrumentingPlugin.instrumentClasses(plugins, instrumentingCL, tmpUninstrumentedDir.toFile(), classesDirectory.toFile()) |
| 53 | + } |
| 54 | + |
| 55 | + static ClassLoader createClassLoader(cp, parent = InstrumentAction.classLoader) { |
| 56 | + return new URLClassLoader(cp*.toURI()*.toURL() as URL[], parent as ClassLoader) |
| 57 | + } |
| 58 | +} |
0 commit comments