Add plugin to buildscript and apply from settings plugin

I’m developing a gradle plugin, that reads external config. That config contains a list of necessary plugins to apply. I then add them to project buildscript classpath, and try to apply them.

Essentially in my settings.gradle I add plugins { id "configurator-plugin" }.
And in the configurator plugin I do

settings.getGradle().beforeProject(project -> {
  var dep = project.getBuildScript().getDependencies()
  dep.add("classpath", "location of custom plugin")
  // and here I'd like to apply it automatically in project

Issue is, they are not loaded yet and thus not visible to gradle’s plugin manager, so applying will fail.

They will be visible in project’s build.gradle, and can be applied manually from there, but I’d rather avoid that.
They are also visible in afterEvaluate, but there it is a bit late to apply.

I tried resolving classpath configuration with no success, before applying plugins, but it did not work (plus it’s a huge hack).

Maybe someone can help me with this?

Iirc the settings script class loader is an ancestor class loader of the build script class loaders.
So can you just add those plugins to the buildscript classpath of the settings script? Then you can probably apply them to the projects.

Thank you for the answer, Björn!

It probably would work, but the issue here is that I’ll be contaminating settings classpath that is shared across all subprojects.

Ideally, I’d like to affect only specific projects.

Your approach shown above also affects all projects.