String & URI Utilities
The StringTools object has many methods to work with string, URIs and regex patterns.
An instance of it can be obtained via ConfigCacheSafeOptions.stringTools()
or ProjectOperations.getStringTools()
.
This instance is configuration cache compatible and can be called from within a task action.
Conversion methods usually take an Object
instance of a collection of Object
as inputs.
They can recursively unpack Callable
, Closure
, Optional
, Provider
and Supplier
until it gets to something it can evaluate.
assert stringTools().stringize(Optional.of(
project.provider { ->
{ ->
{ -> '[bB]?' } as Supplier<String>
} as Callable<String>
}
)).get() == '[bB]?'
When collections are evaluated, they are recursively unpacked so that they end result is one flat collection of items.
assert stringTools().patternize([
[
'.+',
Pattern.compile('.+'),
{ -> '.+' },
],
[
project.provider { -> '.*' },
{ -> '.*?' },
{ -> '.+?' } as Callable<Pattern>,
{ -> '[aA]?' } as Supplier<Pattern>,
Optional.of(
project.provider { ->
{ ->
{ -> '[bB]?' } as Supplier<Pattern>
} as Callable<Pattern>
}
)
]
]
)*.pattern() == ['.+','.+','.+','.*','.*?','.+?','[aA]?','[bB]?']
Converting objects to strings
There a a number of methods that can convert Object
or collections of Object
to String
instances.
Can convert most things to a string.
org.gradle.api.resources.TextResource
instances are also supported.
Unpacking is done recursively until something is found to evaluate.
-
provideString(Object)
- Creates aString
provider to a lazy-evaluatedObject
. -
provideStringOrNull(Object)
- Creates aString
provider to a lazy-evaluatedObject
, but allow fornull
values. -
provideValues(Map<String,?>)
- A provider to something that will converts all values in the map to strings. -
provideValues(Provider<Map<String,?>>)
- Similar to the previous method, but takes a provider to a map as input. -
provideValuesDropNull(Map<String,?>)
- A provider to something that will converts all values in the map to strings. -
provideValuesDropNull(Provider<Map<String,?>)
- Similar to the previous, but takes a provider as input. -
stringize(Object)
- Converts nearly anything to a string. -
stringizeOrNull(Object)
- Like the previous method, but allows fornull
values. -
stringize(Collection<Object>)
- Converts a collection to a list of strings. -
stringizeDropNull(Collection<Object>)
- Converts a collection to a list of strings. If any item in the collection isnull
, it will be removed from the end result. -
stringizeValues(Map<String, ?>)
- Converts the values of the map into strings.null
entries result in an exception being emitted. -
stringizeValuesDropNull(Map<String, ?>)
- Converts the values of the map into strings. If any value isnull
, the key will be removed from the resulting map.
Updating Property<String> instances in-situ.
Gradle’s Property class is two-edged sword. On the one sde it makes lazy-evaluation easier for both Groovy & Kotlin DSLs, bit on the other sides it really messes up the Groovy DSL for build script authors.
The correct way to use is not as field, but as the return type of the getter as illustrated by the following skeleton code
class MyTask extends DefaultTask {
@Input
Property<String> getSampleText() {
this.sampleText
}
void setSampleText(Object txt) {
// ...
}
private final Property<String> sampleText
}
The hard part for the plugin author is to deal with initialisation of the private field and then with further updates. This is where updatePropertyString becomes very useful as the code can now be implemented as.
class MyTask extends DefaultTask {
MyTask() {
sampleText = project.objects.property(String)
sampleText.set('default value')
}
@Input
Property<String> getSampleText() {
this.sampleText
}
void setSampleText(Object txt) {
StringUtils.updatePropertyString(project, sampleText, txt) (1)
}
private final Property<String> sampleText
}
1 | Updates the value of the Property instance, but keeps the txt object lazy-evaluated. |
Working with URIs
Converting objects to URIs
A number of types are supported for conversion to URIs.
This includes an CharSequence
, File
, Path
, URI
, and URL
.
Recursive unpacking is performed.
-
provideUri(Object)
- Provides a URI at a future stage. -
urize
- Convert nearly anything to a URI.
Removing credentials from URIs
Use safeURI
to remove credentials from URIs.
This is especially useful for printing.
Creating a hash from a URI
Use hashUri
to create a SHA256 hash from a URI, which is then hex-encoded.
hashURI('http://example.com'.toURI())
Get the package or filename from URI
Use packageNameFromUri
to extract the last path part from a URI
packageNameFromUri('http://example.com/foo/bar.tgz'.toURI()) == 'bar.tgz'
Working with regex patterns
There a a number of methods that can convert Object
or collections of Object
to java.util.regex.Pattern
instances.
Supported types are anything CharSequence
, Pattern
.
Unpacking is done recursively until something is found to evaluate.
-
patternize(Object)
- Converts to aPattern
.patternizeOrNull(Object)
- Converts to aPattern
. If input isnull
, it returnsnull
, rather than emitting an exception. WrappingProvider
etc. instances that are empty, are treated asnull
patternize(Collection<Object>)
- Converts a collection of objects to a list ofPattern
instances. Will emit an exception if anything in the input is null.patternizeDropNull(Collection<Object>)
- Converts a collection of objects to a list ofPattern
instances. Items in the provided collection that are null, will be dropped. WrappingProvider
etc. instances that are empty, are treated asnull
-
providePattern(Object)
- Create aPattern
provider to a lazy-evaluatedObject
. -
providePatternOrNull(Object)
- Create aPattern
provider to a lazy-evaluatedObject
, which will allow fornull
values.
Loading text
Use loadTextFromResource
to load the contents of a resource on the classpath as a string.
You can also create a lazy version by using provideTextFromResource
.
Converting objects to byte arrays
Certain objects can be converted to byte[]
.
This includes:
-
Character sequences.
-
File instances
-
Path instances if they are on the default file systems
-
byte[]
andByte[]
.
-
makeByteArray(Object)
- Converts to abyte[]
. -
makeByteArrayOrNull(Object)
- Converts to abyte[]
, byt allowsnull
as a valid input. -
provideByteArray(Object)
- A provider to abyte[]
. -
provideByteArrayOrNull(Object)
- A provider to abyte[]
. Anull
input or an empty provider will result in an empty provider returned.