Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions errorprones.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ the tasks become independent and can execute in parallel.

When defining a custom Task or Extension, you should make it an abstract class with abstract getter methods of each of the properties and other gradle containers (eg NamedDomainObjectSet). Gradle will then automatically create the properties and containers, removing a lot of boilerplate. Additionally, as you declare eg `public abstract Property<Integer> getFoo()`, this will automatically make the `foo = 3` groovy syntax work of the box.

</td>
</tr>

<tr>
<td>

<a id="UseGradleExecInsteadOfProviderFactoryExec" href="guide/adopting-the-configuration-cache.md">`UseGradleExecInsteadOfProviderFactoryExec`</a>

</td>
<td>
<a href="guide/adopting-the-configuration-cache.md">Please read</a>
</td>
<td>

Use GradleExec.exec() instead of ProviderFactory.exec(). GradleExec provides configuration cache compatibility, eliminates manual provider zipping, and captures execution context for clear error messages instead of Gradle internal stack traces. It returns a single FallibleProvider combining stdout, stderr, and exit code.

</td>
</tr>
</tbody>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* (c) Copyright 2025 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.gradle.guide.errorprone;

import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;

@AutoService(BugChecker.class)
@BugPattern(
severity = SeverityLevel.ERROR,
summary = "Use GradleExec.exec() instead of ProviderFactory.exec(). "
+ "GradleExec provides configuration cache compatibility, eliminates manual provider zipping, "
+ "and captures execution context for clear error messages instead of Gradle internal stack traces. "
+ "It returns a single FallibleProvider combining stdout, stderr, and exit code.")
public final class UseGradleExecInsteadOfProviderFactoryExec extends GradleGuideBugChecker
implements BugChecker.MethodInvocationTreeMatcher {

private static final Matcher<ExpressionTree> PROVIDER_FACTORY_EXEC = Matchers.instanceMethod()
.onDescendantOf("org.gradle.api.provider.ProviderFactory")
.named("exec");

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (PROVIDER_FACTORY_EXEC.matches(tree, state)) {
return buildDescription(tree).build();
}

return Description.NO_MATCH;
}

@Override
public MoreInfoLink moreInfoLink() {
return new MoreInfoPageLink("adopting-the-configuration-cache.md");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* (c) Copyright 2025 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.gradle.guide.errorprone;

import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.Test;

@SuppressWarnings("MisformattedTestData")
class UseGradleExecInsteadOfProviderFactoryExecTest {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(UseGradleExecInsteadOfProviderFactoryExec.class, getClass());

@Test
void matches_provider_factory_exec() {
compilationTestHelper.addSourceLines(
"Test.java",
// language=java
"""
import org.gradle.api.DefaultTask;
import org.gradle.api.provider.ProviderFactory;
import javax.inject.Inject;

abstract class Test extends DefaultTask {
@Inject
abstract ProviderFactory getProviderFactory();

void doSomething() {
// BUG: Diagnostic contains: Use GradleExec.exec() instead
getProviderFactory().exec(spec -> {
spec.commandLine("echo", "hello");
});

// BUG: Diagnostic contains: Use GradleExec.exec() instead
getProject().getProviders().exec(spec -> {
spec.commandLine("ls");
});
}
}
""");

compilationTestHelper.doTest();
}

@Test
void does_not_match_other_exec_methods() {
compilationTestHelper.addSourceLines(
"Test.java",
// language=java
"""
import org.gradle.api.DefaultTask;
import org.gradle.process.ExecOperations;
import javax.inject.Inject;

abstract class Test extends DefaultTask {
@Inject
abstract ExecOperations getExecOperations();

@Inject
abstract org.gradle.api.provider.ProviderFactory getProviderFactory();

void doSomething() {
// Should NOT be flagged - ExecOperations.exec is fine
getExecOperations().exec(spec -> {
spec.commandLine("echo", "hello");
});

// Should NOT be flagged - other ProviderFactory methods
getProviderFactory().provider(() -> "hello");
getProviderFactory().environmentVariable("PATH");
}
}
""");

compilationTestHelper.expectNoDiagnostics().doTest();
}

@Test
void suppressed_calls_should_pass() {
compilationTestHelper.addSourceLines(
"Test.java",
// language=java
"""
import org.gradle.api.DefaultTask;
import org.gradle.api.provider.ProviderFactory;
import javax.inject.Inject;

abstract class Test extends DefaultTask {
@Inject
abstract ProviderFactory getProviderFactory();

@SuppressWarnings("UseGradleExecInsteadOfProviderFactoryExec")
void doSomething() {
getProviderFactory().exec(spec -> {
spec.commandLine("echo", "suppressed");
});
}
}
""");

compilationTestHelper.expectNoDiagnostics().doTest();
}
}
20 changes: 11 additions & 9 deletions guide/adopting-the-configuration-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,11 @@ abstract class MyPlugin implements Plugin<Project> {

#### After

- To safely do an external call during the configuration phase, we can use the `ProviderFactory` service.
- To use `ProviderFactory`, we can inject it into `MyPlugin`.
- To safely do an external call during the configuration phase, we can use the [`GradleExec`](https://github.com/palantir/gradle-utils?tab=readme-ov-file#gradleexec) service.
- To use `GradleExec`, we can inject it into `MyPlugin`.
Comment thread
FinlayRJW marked this conversation as resolved.

> [!NOTE]
> [`GradleExec`](https://github.com/palantir/gradle-utils?tab=readme-ov-file#gradleexec) is our version of `ProviderExec` with better error handling and readable stack traces.

> [!NOTE]
> To inject a service, make a protected/public abstract getter method returning that service. It has to be prefixed with `get-` for Gradle's injection to work properly!.
Expand All @@ -195,14 +198,13 @@ abstract class MyPlugin implements Plugin<Project> {

```java
abstract class MyPlugin implements Plugin<Project> {
@Inject
protected abstract ProviderFactory getProviderFactory();
@Nested
protected abstract GradleExec getGradleExec();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's test that this compiles!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


private Provider<String> latestTag = getProviderFactory()
Provider<String> latestTag = gradleExec
.exec(execSpec -> execSpec.setCommandLine("git", "describe", "--tags", "--abbrev=0"))
.getStandardOutput()
.getAsText()
.map(String::trim);
.map(GradleExecResult::stdOut)
.map(String::trim);

@Override
public final void apply(Project project) {
Expand All @@ -215,7 +217,7 @@ abstract class MyPlugin implements Plugin<Project> {
```

> [!TIP]
> If you call `ProviderFactory#exec` multiple times in your code, the external process `git describe` will run each time.
> If you call `GradleExec#exec` multiple times in your code, the external process `git describe` will run each time.
>
> Instead, store the `Provider` in a field as shown above. With this approach, the `Provider` caches the result, and git describe runs only once, even if `latestTag.get()` is called multiple times.

Expand Down