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.

Recursive evaluation

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.

Recursive evaluated example
assert stringTools().stringize(Optional.of(
    project.provider { ->
        { ->
            { -> '[bB]?' } as Supplier<String>
        } as Callable<String>
    }
)).get() == '[bB]?'
Flattening collections

When collections are evaluated, they are recursively unpacked so that they end result is one flat collection of items.

Example of flattened collection evaluation
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.

Methods

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.

Methods

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.

Methods
  • patternize(Object) - Converts to a Pattern. patternizeOrNull(Object) - Converts to a Pattern. If input is null, it returns null, rather than emitting an exception. Wrapping Provider etc. instances that are empty, are treated as null patternize(Collection<Object>) - Converts a collection of objects to a list of Pattern instances. Will emit an exception if anything in the input is null. patternizeDropNull(Collection<Object>) - Converts a collection of objects to a list of Pattern instances. Items in the provided collection that are null, will be dropped. Wrapping Provider etc. instances that are empty, are treated as null

  • providePattern(Object) - Create a Pattern provider to a lazy-evaluated Object.

  • providePatternOrNull(Object) - Create a Pattern provider to a lazy-evaluated Object, which will allow for null 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[] and Byte[].

Methods