How to properly append to the JavaExec and Test task classpaths?

I recently had luck getting subsets of the runtimeClasspath using ArtifactView.componentFilter { ... } for separating out library jars and project jars for ProGuard. That inspired me to take another stab at getting resource subsets by attribute.

I made numerous varying attempts at getting manual filtering to work, but everything I tried failed on one error or another. I gave up on that approach, and dug my heels in on the attribute matching approach instead. I finally got that to work.

The trick was to not add a variant with a new attribute, but instead add a variant with a new value for the existing org.gradle.libraryelements attribute. That seems to not fight the variant matching algorithm and existing compatibility and disambiguation rules at play for the runtimeClasspath configuration.

I generalized it into a plugin. I haven’t extracted it from my test project and published it, but here’s the source in case anyone else ever finds this and has the same need:

Example of use: