T
- The type of value obtained from this source.P
- The source specific parameter type.public interface ValueSource<T,P extends ValueSourceParameters>
Representing external sources as ValueSource
s allows Gradle to transparently manage
the configuration cache
as values obtained from those sources change.
For example, a build might run a different set of tasks depending on whether the CI
environment variable is set or not.
To integrate a new type of value source, create an abstract subclass of this interface
and use ProviderFactory.of(Class, Action)
to get a provider to a configured source.
The returned Provider
can be passed to tasks or queried
by build logic during the configuration phase. In the latter case, the source would be automatically
considered as an input to the work graph cache.
It is possible to have some Gradle services to be injected into the implementation, similar to
tasks and plugins. It can be done by adding a parameter to the constructor and annotating the
constructor with the @Inject
annotation:
public class MyValueSource implements ValueSource<...> { @Inject public MyValueSource(ExecOperations execOperations) { ... } }Currently, only a small subset of services is supported:
ExecOperations
provides means to execute external processes.
It is possible to use this service even at configuration time. However, as the
returned value is used to check the configuration cache, the obtain()
method will
be called during each build. Calling slow commands here will slow things down.
A value source implementation will most likely take parameters. To do this create a
subtype of ValueSourceParameters
and declare this type as the type parameter
to the value source implementation.
A value source implementation doesn't have to be thread-safe, as the single call
to obtain()
is synchronized.
A value source implementation is exempt from the automatic detection of work graph cache inputs.
For example, if the obtain()
method calls System.getenv("FOO")
then changes to
the FOO
environment variable only invalidate the cache if the value returned by the
obtain()
method itself changes. The same applies to reading files or system properties.
Starting an external process with a standard API (for example, java.lang.ProcessBuilder
) is
also allowed.
Modifier and Type | Method | Description |
---|---|---|
P |
getParameters() |
The object provided by
ValueSourceSpec.getParameters() when creating a provider from the value source. |
T |
obtain() |
Obtains the value from the source.
|
@Inject P getParameters()
ValueSourceSpec.getParameters()
when creating a provider from the value source.
Do not implement this method in your subclass.
Gradle provides the implementation when creating a provider from the value source via ProviderFactory.of(Class, Action)
.
@Nullable T obtain()
This method must be implemented in the subclass.
This method is only called if the provider value is requested and only once in that case.
null
if the value is not present.